How to create a stream providing f (n) = f (n-2) + f (n-3) in scala

I've tried this:

val s1:Stream[Int]=1 #:: 0 #:: 1 #:: 1 #:: (s1.tail.tail.tail,s1.tail.tail).zipped.map{(c,d) => c + d}.toStream

      

but

s1(5)

      

calls stackoverflow ...

I was able to write the correct definition with two parameters:

val s2:Stream[Int]=1 #:: 0 #:: 1 #:: 1 #:: (s2.tail.tail.tail.zip(s2.tail.tail)).map{n=> n._1+n._2}

      

but in the future I will want to add more than two lists, so I would like to use "zipped" instead of "zip".

thank

+3


source to share


2 answers


How about Stream.iterate((1, 0, 1))({case (a, b, c) => (b, c, a + b)}).map(_._3)

?



+1


source


It looks like this code does your sequence correctly:

val s:Stream[Int]=1 #:: 0 #:: 1 #:: 1 #:: (s.tail zip s.tail.tail).map {t => t._1 + t._2}

      



For example:

s(7) = 3
s(8) = 4
s(10) = 7

      

0


source







All Articles