简体   繁体   English

在Scala中尝试Haskell风格的惰性评估时出现堆栈溢出错误

[英]Getting stack overflow error when trying Haskell-style lazy evaluation in Scala

To practice, I'm writing some useless methods/functions in Scala. 为了练习,我在Scala中编写了一些无用的方法/函数。 I'm trying to implement a fibonacci sequence function. 我正在尝试实现斐波那契序列函数。 I wrote one in Haskell to use as a reference (so I don't just end up writing it Java-style). 我用Haskell编写了一个作为参考(因此,我不只是以Java风格编写了它)。 What I've come up with in Haskell is: 我在Haskell中提出的是:

fib a b = c : (fib b c)
   where c = a+b

Then I can do this: 然后我可以这样做:

take 20 (fib 0 1)
[1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946]

So I tried translating this to Scala: 所以我尝试将其翻译为Scala:

def fib(a:Int, b:Int):List[Int] = {
  val c = a+b
  c :: fib(b,c)
}

But I get a stack overflow error when I try to use it. 但是,当我尝试使用它时,出现堆栈溢出错误。 Is there something I have to do to get lazy evaluation to work in Scala? 我需要做一些事情才能获得懒惰的评估才能在Scala中工作吗?

Lists in scala are not lazily evaluated. scala中的列表不会被懒惰地评估。 You have to use a stream instead: 您必须改用流:

def fib(a:Int, b:Int): Stream[Int] = {
  val c = a+b
  c #:: fib(b,c)
}

scala> fib(0,1) take 20 toList
res5: List[Int] = List(1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946)

While @drexin's answer is generally correct, you might want to use a lazy val instead of just a val in some cases; 虽然@drexin的答案通常是正确的,但在某些情况下,您可能希望使用lazy val而不是仅使用val see here for some more information on lazy val s. 请参阅此处以获取有关lazy val的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM