Scala函数式编程课后习题答案(第五章)
没有按题目细分,比较杂乱。
比较杂的练习数据1
object Stream {
sealed trait Stream[+A] {
def uncons: Option[(A, Stream[A])]
def isEmpty: Boolean = uncons.isEmpty
def toList:List[A]={
@annotation.tailrec //尾递归标记,用于检测是否是尾递归
def go(s:Stream[A], acc: List[A]): List[A] ={
s.uncons match {
case None => acc
case Some((h,t)) => go(t,h::acc)
}
}
go(this,Nil).reverse
}
def toListFast:List[A] ={
val buf = new collection.mutable.ListBuffer[A]
@annotation.tailrec
def go(s:Stream[A]):List[A] ={
s.uncons match {
case Some((h,t)) => {
buf += h
go(t)
}
case _ => buf.toList
}
}
go(this)
}
def take(n:Int):Stream[A] = {
if(n==0) empty
else
uncons match {
case None => empty
case Some((h,t)) => cons(h,t.take(n-1))
}
}
def drop(n:Int):Stream[A]={
if (n ==0) this
else
uncons match {
case Some((h,t)) => t.drop(n-1)
case _ => this
}
}
def dropWhile(p: A => Boolean): Stream[A] ={
uncons match {
case None => empty
case Some((h,t)) => if(p(h)) t.dropWhile(p) else t
}
}
def foldRight[B](z: =>B)(f: (A, =>B) =>B):B =
uncons match {
case None =