流中的懒惰评估?

时间:2015-03-26 01:22:27

标签: scala stream

给出lazy val

scala> lazy val y = {println("Y!"); 200}
y: Int = <lazy>

我尝试将y放入Stream - 以确定是否会急切或懒惰地评估。

scala> Stream(100, y)
Y!
res4: scala.collection.immutable.Stream[Int] = Stream(100, ?)

显然,它受到了热切的评价。

除了以下内容,我如何创建一个懒惰评估其成员的Stream

scala> Stream[() => Int](() => 100, () => 200)
res18: scala.collection.immutable.Stream[() => Int] = Stream(<function0>, ?)

scala> res18.map(_())
res19: scala.collection.immutable.Stream[Int] = Stream(100, ?)

scala> res19.last
res20: Int = 200

scala> res19
res21: scala.collection.immutable.Stream[Int] = Stream(100, 200)

2 个答案:

答案 0 :(得分:5)

Stream.apply采用varargs参数,并且在Scala中不可能有名称的varargs参数。但是,您可以使用流的#::语法:

scala> lazy val y = {println("Y!"); 200}
y: Int = <lazy>

scala> val s = 100 #:: y #:: Stream.empty
s: scala.collection.immutable.Stream[Int] = Stream(100, ?)

scala> s.last
Y!
res0: Int = 200

这是有效的,因为ConsWrapper类和用于向流添加#::的隐式转换都采用了名称参数。

答案 1 :(得分:0)

特拉维斯是对的,但仅仅是为了踢球:

scala> implicit def a2f[T](t : => T) : (() => T) = () => t
a2f: [T](t: => T)() => T

scala> def lazyStream[T]( args : (() => T)* ) : Stream[T] = Stream(args:_*).map(_())
lazyStream: [T](args: () => T*)Stream[T]

scala> lazy val y = {println("Y!"); 200}
y: Int = <lazy>

scala> lazyStream(100, y)
res8: Stream[Int] = Stream(100, ?)

scala> res8.last
Y!
res9: Int = 200