Scala函数式编程课后习题答案(第三章)(更新ing)
练习3.9
def foldRight[A,B](as:List[A],z:B)(f:(A,B) =>B):B=as match {
case Nil =>z
case ::(x,xs) => f(x,foldRight(xs,z)(f))
}
def length[A](as:List[A]):Int =foldRight(as,0)((_,xs)=>xs+1)
练习3.10 3.13
def foldLeft[A,B](as:List[A],z:B)(f:(B,A)=>B):B = as match {
case Nil =>z
case ::(x,xs) =>foldLeft(xs,f(z,x))(f)
}
练习3.11
def foldLeft[A,B](as:List[A],z:B)(f:(B,A)=>B):B = as match {
case Nil =>z
case ::(x,xs) =>foldLeft(xs,f(z,x))(f)
}
def sum3(ns:List[Int])=foldLeft(ns,0)(_+_)
def product3(ns:List[Double])=foldLeft(ns,1.0)(_*_)
练习3.14
def foldLeft[A,B](as:List[A],z:B)(f:(B,A)=>B):B = as match {
case Nil =>z
case ::(x,xs) =>foldLeft(xs,f(z,x))(f)
}
def append[A](as:List[A],a:List[A]):List[A] = foldLeft(as.reverse,a){(x,xs)=> ::(xs,x)}
练习3.15
def foldLeft[A,B](as:List[A],z:B)(f:(B,A)=>B):B = as match {
case Nil =>z
case ::(x,xs) =>foldLeft(xs,f(z,x))(f)
}
def append[A](as:List[A],a:List[A]):List[A] = foldLeft(as.reverse,a){(x,xs)=> ::(xs,x)}
def concat[A](ll:List[List[A]]):List[A]=foldLeft(ll,Nil:List[A]){append}
练习3.16 3.17 3.18
def foldLeft[A,B](as:List[A],z:B)(f:(B,A)=>B):B = as match {
case Nil =>z
case ::(x,xs) =>foldLeft(xs,f(z,x))(f)
}
def map_2[A,B](l: List[A])(f: A => B): List[B] = foldLeft(l.reverse,Nil: List[B]){(h,acc) => ::(f(acc),h)}
练习3.19
def foldLeft[A,B](as:List[A],z:B)(f:(B,A)=>B):B = as match {
case Nil =>z
case ::(x,xs) =>foldLeft(xs,f(z,x))(f)
}
def filter_2[A](as: List[A])(f: A => Boolean):List[A]= foldLeft(as.reverse,Nil: List[A]){(h,acc) =>if(f(acc)) ::(acc,h) else h}
练习3.20
def foldLeft[A,B](as:List[A],z:B)(f:(B,A)=>B):B = as match {
case Nil =>z
case ::(x,xs) =>foldLeft(xs,f(z,x))(f)
}
def flatMap_2[A,B](l: List[A])(f: A => List[B]): List[B] = concat(map_2(l)(f))
练习3.24
def compareList[A](as:List[A],a:List[A]):Boolean = (as,a) match{
case (_,Nil) => true
case (::(x1,xs1),::(x2,xs2)) if(x1==x2) => compareList(xs1,xs2)
case (::(x1,xs1),::(x2,xs2)) if(x1!=x2) => compareList(xs1,::(x2,xs2))
case _ =>false
}
练习3.25 3.26 3.27 3.28 3.29
sealed trait Tree[+A]
{
def size: Int = this match {
case Leaf(_) => 1
case Branch(l,r) => 1 + l.size + r.size
}
def maximum: Int = this match {
case Leaf(a:Int) => a
case Branch(l,r) => l.maximum max r.maximum
}
def depth:Int = this match {
case Leaf(_) =>0
case Branch(l,r) => 1 +(l.depth max r.depth)
}
def map(f:Int=>Int):Tree[Int] = this match {
case Leaf(x:Int) => Leaf(f(x))
case Branch(l,r) => Branch(l.map(f),r.map(f))
}
def fold[B](f:A=>B)(g:(B,B)=>B):B =this match {
case Leaf(n) => f(n)
case Branch(l,r) => g(l.fold(f)(g),r.fold(f)(g))
}
def sizeByfold = fold(_=>1)(1+_+_)
def maximumByfold(ll:Tree[Int]) = ll.fold(a =>a)((l,r)=>0+(l max r))
def depthByfold = fold(_=>0)((l,r)=>1+(l max r))
}
case class Leaf[A](value: A) extends Tree[A]
case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]