20160331 Nguyên lý ngôn ngữ lập trình
package exercisepackage exercise
trait FP {
// Q1 def recLstSquare(n:Int):List[Int]={ if(n==1) List(1) return recLstSquare(n-1) ++ List(n*n) } def recHelpLstSquare(n1:Int,n2:Int):List[Int] = { if(n1==n2) List(n2*n2) else (n1*n1)::recHelpLstSquare(n1+1, n2) } def higLstSquare(n:Int):List[Int]{ //return (1 to n).map(n => n*n).toList }// Q2 def recPow(x:Double,n:Int):Double = { if(n==0) 1 else x * recPow(x, n-1) } def higPow(x:Double,n:Int):Double = (1 to n).toList.foldLeft(10)*1((x,y)=>y::x) }// Q4 def LessThan(n:Int,lst:List[Int]):List[Int] = null def recLessThan(n:Int,lst:List[Int]):List[Int] = { if(lst.isEmpty) lst else{ if(lst.head < n) lst.head::recLessThan(n, lst.tail) else recLessThan(n, lst.tail) } } def higLessThan(n:Int,lst:List[Int]) = null
// Q5 case class A(n:String,v:Int) case class B(x:Int,y:A) def lookup[T](n:String,lst:List[T],f:T=>String):Option[T] = { if(lst.isEmpty) null else{ if(f(lst.head)==n) Some(lst.head) else lookup(n, lst.tail, f) } }}
object Main { def main(args: Array[String]) { //debug message println("This is a main functuion") val LnSqare = new Array[Int](10) }}
*1:a,b)=>a*n)// Q3 def recAppend(a:List[Int],b:List[Int]):List[Int] = { if(a.isEmpty) return b else return a.head::recAppend(a.tail,b) } def recReverse(a:List[Int]):List[Int] = { a match { case List() => a case head::tail => recReverse(tail):+head } } def higAppend(a:List[Int],b:List[Int]) = null def higReverse(a:List[Int]):List[Int] = { a.foldLeft(List[Int](