Search code examples
haskellfibonacci

Fibonacci Sequence in Haskell - only return values up to a user input value NOT index


I have seen many Haskell programs that when a user enters 5 it will return the first 5 elements of the Fibonacci sequence, however, I need it to only output the values of the Fibonacci sequence that are less than or equal to 5.

For example: Fib 15 needs to output 1 1 2 3 5 8 13

Fib 7 needs to output 1 1 2 3 5

This is what I have & am trying to alter to output up to the given value and not the given index:

    -- individual fib numbers
    fib :: Int -> Int
    fib 0 = 1
    fib 1 = 1
    fib n = fib (n - 1) + fib (n - 2)

    -- example run fib 6 returns the int at position 6 
    -- so fib 6 = 13


    -- combines individual fib numbers
    fibonacciSequence x = map fib[1..x]

Some things I have tried:

    fibonacciSequence x = map (\x -> fib[1..] > x ) [1..]

    y = filter (\y -> y > x) fib[1..x]

    fibonacciSequence x = map (inRange (1,x)) [1..]

    fibonaci g = map fst (iterate f (0,1)) where f (x,y) = (y,x+y) | f(y, x+y) <= g

I am very new to Haskell and your help would be very appreciated!


Solution

  • Rather than writing a function that generates a finite sequence like:

    fibonacciSequence x = map fib [1..x]
    

    It is often more useful to write it as an infinite sequence:

    fibonacciSequence = map fib [1..]
    

    Then you can choose which parts you want freely, for the first n elements you can use:

    take n fibonacciSequence
    

    And if you want the Fibonacci numbers up to n you can do it like this:

    takeWhile (<= n) fibonacciSequence