object E7 {
def next_prime(primes: List[Int]) = primes match {
case ps@(h :: t) => {
// Version 1
val rpq = ps.reverse.exists _
// Version 2
val rpq = ps.reverse.exists(_)
(Iterator.from(h + 1).find((v) => ! rpq(v % _ == 0)): @unchecked) match {
case Some(v) => v :: ps
}
}
case Nil => List(2)
}
val primes = Iterator.iterate(List[Int]())(next_prime)
def main(args: Array[String]) {
println(primes.drop(20001).next.head)
}
}
Run Code Online (Sandbox Code Playgroud)
第一个版本完成3.6秒,第二个 - 19.3秒!有什么不同?
编辑:Scala版本2.9.2(Java HotSpot(TM)64位服务器VM,Java 1.7.0_21)
它是如何在 Scala 中完成的:
sealed trait Option[+A] {
def get: A
def isEmpty: Boolean
def map[B](f: A => B): Option[B] =
if (isEmpty) None else Some(f(this.get))
}
object None extends Option[Nothing] {
def isEmpty = true
def get = throw new NoSuchElementException("None.get")
}
case class Some[+A](x: A) extends Option[A] {
def isEmpty = false
def get = x
}
Run Code Online (Sandbox Code Playgroud)
我如何在面向对象世界中假设它:
sealed trait Option[+A] {
def map[B](f: A => B): Option[B]
}
object None extends Option[Nothing] {
def map[B](f: Nothing => B): …Run Code Online (Sandbox Code Playgroud) scala> val s = for(i <- (1 to 10).toStream) yield { println(i); i }
1
s: scala.collection.immutable.Stream[Int] = Stream(1, ?)
scala> s.take(8).toList
2
3
4
5
6
7
8
res15: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)
scala> s.take(8).toList
res16: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)
Run Code Online (Sandbox Code Playgroud)
看起来Scala将流值存储在内存中以优化访问.这意味着它Stream不能用作命令循环的替代,因为它将分配内存.事情(for(i <- (1 to 1000000).toStream, j <- (1 to 1000000).toStream) yield ...).reduceLeft(...)会因为记忆而失败.以这种方式使用流是错误的想法吗?
scala ×3