【发布时间】:2016-08-01 19:01:52
【问题描述】:
我正在玩 scala 流。
这是从给定数字开始的所有整数的流。
我添加了一个println 来跟踪对 from 函数的每次调用。
def from(n: Int): Stream[Int] = n #:: from({ println(n); n + 1 })
val nats = from(0) //> nats : Stream[Int] = Stream(0, ?)
nats.take(4).toList //> 0
//| 1
//| 2
//| 3
//| res0: List[Int] = List(0, 1, 2, 3, 4)
正如预期的那样,这是我的 scala 工作表的输出。然后我创建了所有素数的流。
def sieve(s: Stream[Int]): Stream[Int] = {
s.head #:: sieve(s.tail.filter({ println( "---" ); _ % s.head != 0 }))
} //> sieve: (s: Stream[Int])Stream[Int]
val primes = sieve(from(2))//> primes : Stream[Int] = Stream(2, ?)
primes.take(4).toList //> 2
//| ---
//| 3
//| 4
//| ---
//| 5
//| 6
//| ---
//| res1: List[Int] = List(2, 3, 5, 7)
问题来了。我做了一些我认为应该做的小改动,添加了x 参数而不是_ 占位符。令人惊讶的是,输出完全不同:
def sieve(s: Stream[Int]): Stream[Int] = {
s.head #:: sieve(s.tail.filter(x => { println("---"); (x % s.head) != 0 }))
} //> sieve: (s: Stream[Int])Stream[Int]
val primes = sieve(from(2))//> primes : Stream[Int] = Stream(2, ?)
primes.take(4).toList //> 2
//| ---
//| 3
//| ---
//| 4
//| ---
//| ---
//| 5
//| ---
//| 6
//| ---
//| ---
//| ---
//| res1: List[Int] = List(2, 3, 5, 7)
我不明白为什么所有这些重复。 使用显式参数有什么问题?
【问题讨论】: