【发布时间】:2018-10-23 08:15:46
【问题描述】:
我正在阅读Scala 中的函数式编程一书中包含的示例和练习,并从中获得乐趣。我正在研究严格和懒惰一章,讨论Stream。
我无法理解以下代码摘录产生的输出:
sealed trait Stream[+A]{
def foldRight[B](z: => B)(f: (A, => B) => B): B =
this match {
case Cons(h,t) => f(h(), t().foldRight(z)(f))
case _ => z
}
def map[B](f: A => B): Stream[B] = foldRight(Stream.empty[B])((h,t) => {println(s"map h:$h"); Stream.cons(f(h), t)})
def filter(f:A=>Boolean):Stream[A] = foldRight(Stream.empty[A])((h,t) => {println(s"filter h:$h"); if(f(h)) Stream.cons(h,t) else t})
}
case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]
object Stream {
def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
lazy val head = hd
lazy val tail = tl
Cons(() => head, () => tail)
}
def empty[A]: Stream[A] = Empty
def apply[A](as: A*): Stream[A] =
if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))
}
Stream(1,2,3,4,5,6).map(_+10).filter(_%2==0)
当我执行此代码时,我会收到以下输出:
map h:1
filter h:11
map h:2
filter h:12
我的问题是:
- 为什么地图和过滤器输出是交错的?
- 您能否解释一下涉及的所有步骤,从创建流到获得此行为的最后一步?
- 列表中也通过过滤器转换的其他元素在哪里,所以 4 和 6?
【问题讨论】:
-
我认为最后一个问题是不正确的。就像流一样,我希望根本没有打印。你没有消费流;你只是在改造它。
标签: scala functional-programming stream lazy-evaluation scala-collections