HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Producing full list of Fibonacci numbers which fit in an Int

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fullproducingfibonaccinumbersintwhichlistfit

Problem

I am progressing through the problems listed at projecteuler.com as I learn Scala (my blog where I am covering this experience). I have written a function to produce all the Fibonacci numbers possible in an Int (it's only 47). However, the resulting function feels imperative (not functional).

val fibsAll = {
    //generate all 47 for an Int
    var fibs = 0 :: List()
    var current = fibs.head
    var next = 1
    var continue = true
    while (continue) {
      current = fibs.head
      fibs = next :: fibs
      continue = ((0.0 + next + current) <= Int.MaxValue)
      if (continue)
        next = next + current
    }
    fibs.reverse
  }


I am looking for feedback on this code:

  • To what degree does the presence of even a single var (there are four here) indicate an erred approach from a functional standpoint?



  • Given I want to return a List[Int], what better way is there to do this recursively as opposed to my current (odd) "while loop" approach?



I am finding the transition from imperative to functional thinking quite challenging.

Solution

object Euler002 extends App{
  // Infinite List (Stream) of Fibonacci numbers 
  def fib(a: Int = 0, b: Int = 1): Stream[Int] = Stream.cons(a, fib(b, a+b)) 

  // Take how many numbers you want into a List 
  val fibsAll = fib() takeWhile {_>=0} toList
  fibsAll reverse 
}


Take a look at this.

Code Snippets

object Euler002 extends App{
  // Infinite List (Stream) of Fibonacci numbers 
  def fib(a: Int = 0, b: Int = 1): Stream[Int] = Stream.cons(a, fib(b, a+b)) 

  // Take how many numbers you want into a List 
  val fibsAll = fib() takeWhile {_>=0} toList
  fibsAll reverse 
}

Context

StackExchange Code Review Q#3619, answer score: 6

Revisions (0)

No revisions yet.