Scala函数式编程课后习题答案(第五章)

这篇博客整理了Scala函数式编程课程第五章的课后习题答案,包括两个部分:比较杂的练习数据1和2,内容涵盖广泛的函数式编程练习。
摘要由CSDN通过智能技术生成

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 =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值