在Scala中尝试Haskell式懒惰评估时出现堆栈溢出错误 [英] Getting stack overflow error when trying Haskell-style lazy evaluation in Scala

查看:121
本文介绍了在Scala中尝试Haskell式懒惰评估时出现堆栈溢出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了练习,我在Scala中编写了一些无用的方法/函数。我试图实现一个斐波那契序列函数。我在Haskell中写了一个作为参考(所以我不只是写它Java风格)。我在Haskell中提出的是:

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

然后我可以这样做:

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

所以我试着把它翻译成Scala:

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

但是当我尝试时出现堆栈溢出错误使用它。有什么我必须做的,以获得懒惰的评估工作在斯卡拉?

解决方案

scala中的列表不会被延迟评估。您必须使用流:

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

scala> fib(0,1)取20到列表
res5:列表[Int] =列表(1,2,3,5,8,13,21,34,55,89,143,23,37,510, 987,1597,2584,4181,6765,10946)


To practice, I'm writing some useless methods/functions in 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). What I've come up with in Haskell is:

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:

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?

解决方案

Lists in scala are not lazily evaluated. 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)

这篇关于在Scala中尝试Haskell式懒惰评估时出现堆栈溢出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆