scala - How to return a stream of the first N Fibonacci numbers? -
i'm trying return stream of first n fibonacci n given parameter. lets if pass 6 function should "0,1,1,2,3,5" or if pass 7 should "0,1,1,2,3,5,8" , on. ideas on how accomplish this?.
here have far:
def fibonacci(n: int): stream[int] = { if (n == 0) return 0; if (n<= 2) return 1; fibterm = fibonacci(n - 1) + fibonacci(n - 2); return fibterm; }
create fibonacci stream.
val fib: stream[int] = 0 #:: fib.scan(1)(_+_)
take n
elements it.
fib.take(n)
here how can add in function:
def fibonacci(n: int): stream[int] = { lazy val fib: stream[int] = 0 #:: fib.scan(1)(_+_) fib.take(n) }
note lazy
needed otherwise compiler gets confused , gives: "<> error: forward reference extends on definition of value fib"
Comments
Post a Comment