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)(_*_)