首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Martin Odersky Scala编程公开课 第一周功课

2013-09-26 
Martin Odersky Scala编程公开课 第一周作业Functional Programming Principles in Scala by Martin Oders

Martin Odersky Scala编程公开课 第一周作业

Functional Programming Principles in Scala 
by Martin OderskyMartin教授是scala语言的creator,在coursera上面有scala课程。本文是第一周的作业。
作业应该做Eclipse里面编辑,使用WorkSheet实时检查。然后使用sbt运行styleCheck,test命令进行测试,run命令来运行main函数,如果没有错误,就可使用submit命令提交作业了。
本周作业不难。pascal三角需要注意运算过程中尽量不要超出Int的表示范围;我在程序中使用了一个小技巧来做到这一点。balance程序需要使用多个if else 来控制流程。countChange则使用迭代的方法实现,如果没有想起来这个方法会比较难。还要注意程序什么条件下终止。
作业要求:
package recfunimport common._object Main {  def main(args: Array[String]) {    println("Pascal's Triangle")    for (row <- 0 to 10) {//change to 22 to check pascal if out of Int range      for (col <- 0 to row)        print(pascal(col, row) + " ")      println()    }  }  /**   * Exercise 1   */  def pascal(c: Int, r: Int): Int = {    //everytime mutiply a little num in case of overflow Int rangedef factB(c: Int, r: Int): Int =if (c==0) 1 else factB(c-1,r)*(r-c+1)/cfactB(c,r)  }  /**   * Exercise 2   */  def balance(chars: List[Char]): Boolean ={  def count(char:Char):Int ={  if (char == '(') 1  else if (char == ')') -1  else 0  }  def isOK(len:Int,chars:List[Char]):Boolean={  if (chars.isEmpty) len==0  else if (len==0 && count(chars.head) == -1) false  else isOK(len+count(chars.head),chars.tail)  }  isOK(0,chars)  }  /**   * Exercise 3   */  def countChange(money: Int, coins: List[Int]): Int =if (money==0) 1else if (coins.isEmpty || money<0) 0else countChange(money,coins.tail)+countChange(money-coins.head,coins)}


热点排行