【发布时间】:2013-04-15 18:02:00
【问题描述】:
有一种模式反复出现我一直没能完全理解,比如下面code计算isPrime
class S99Int(val start: Int) {
import S99Int._
def isPrime: Boolean =
(start > 1) && (primes takeWhile ( _ <= Math.sqrt(start) ) forall ( start % _ != 0 ))
}
object S99Int {
implicit def int2S99Int(i: Int): S99Int = new S99Int(i)
val primes = Stream.cons(2, Stream.from(3, 2) filter { _.isPrime })
}
import S99Int._
24 isPrime //returns false
我不明白的是:filter 中的primes 使用isPrime。但是def isPrime 再次使用相同的primes 来获取元素。这不就像一个无限循环,一件事问另一件事,然后那件事又问自己。尽管代码运行良好。
【问题讨论】:
-
查看stackoverflow.com/questions/15594227/… 了解类似问题。
标签: scala