Here’s a short practice exercise to help you solidify your understanding of Haskell:
Exercise: Fibonacci sequence
In this exercise, you’ll write a Haskell function to generate the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding numbers. The first two numbers in the sequence are 0 and 1, and the sequence continues indefinitely.
- Define a Haskell function called
fibonaccithat takes an integer
nand returns a list containing the first
nnumbers of the Fibonacci sequence.
- Here’s an example of what the
fibonaccifunction should return for different values of
fibonacci 0 =>  fibonacci 1 =>  fibonacci 2 => [0, 1] fibonacci 5 => [0, 1, 1, 2, 3]
- Once you’ve defined your
fibonaccifunction, try using it to generate the first 20 numbers of the Fibonacci sequence.
Here’s a possible solution to the exercise:
fibonacci :: Int -> [Int] fibonacci 0 =  fibonacci 1 =  fibonacci n = take n fibs where fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
In this solution, we use pattern matching to handle the cases where
n is 0 or 1, and we use the
take function to generate a list containing the first
n numbers of the Fibonacci sequence.
The actual sequence is generated using the
fibs list, which starts with the values 0 and 1, and then uses
zipWith to generate the rest of the sequence. The
zipWith function takes two lists and applies a function to each pair of elements to generate a new list. In this case, we’re using the
+ function to add the previous two elements of the
fibs list together.
To generate the first 20 numbers of the Fibonacci sequence, you can simply call the
fibonacci function with an argument of 20:
*Main> fibonacci 20 [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]
This should generate a list containing the first 20 numbers of the Fibonacci sequence.
Add a Comment