Getting an error while trying a lazy Haskell type evaluation in Scala

To practice, I write some useless methods / functions in Scala. I am trying to implement a fibonacci sequence function. I wrote one in Haskell for use as a reference (so I don't just end up writing it in the Java style). What I found in Haskell:

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

Then I can do it:

 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 to translate this to Scala:

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

But when I try to use it, I get an error. Is there something I need to do to get a lazy grade for working in Scala?

+4
source share
2 answers

Lists in scala are not evaluated lazily. Instead, you should use a stream:

 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) 
+11
source

While @drexin's answer is generally correct, you can use lazy val instead of just val in some cases; see here for more information on lazy val s.

0
source

Source: https://habr.com/ru/post/1485194/


All Articles