0

I'm doing an assignment for a class where my function should return a fibonacci sequence up until a given position. I'm trying to reduce my code in the third case of this code.

object FibonacciSeries{

    def fibrec(pos: Int, list: List[Int] = List() ):List[Int] = pos match {
        case 0 => List(0)
        case 1 => List(0,1)
        case _ => {
                var seq= fibrec(pos - 1 , list)
                seq :+ seq.takeRight(2).sum
        }
    }
}

I want to do it in such a way that only calls the recursive function once, and also fits into one line. I was hoping to do something like.

fibrec(pos -1, list).takeRight(2).sum.append

but I know that won't do. Any help is appreciated

Suavocado
  • 949
  • 12
  • 27
  • You can consider using a `Stream` for your task. Fibonacci sequence is an idiomatic application for scala streams: http://stackoverflow.com/questions/8659127/how-to-fix-my-fibonacci-stream-in-scala – Aivean Sep 23 '15 at 23:04

1 Answers1

2

The link that @Aivean has given offers a few good ways to achieve a Fibonacci stream. This one, however, is the most concise I've encountered.

val fib: Stream[Int] = 0 #:: fib.scan(1)(_+_)
jwvh
  • 50,871
  • 7
  • 38
  • 64