nz_21
nz_21

Reputation: 7343

GHCI: how to save state on Prelude repl?

I am trying to execute fibonacci on the prelude repl but I'm running into an infinite loop:

Prelude> fib 0 = 1
Prelude> fib 1 = 1
Prelude> fib n = fib(n-1) + fib(n-2)
Prelude>
Prelude> fib 3
<loops infinitely...>

How do I fix this?

Upvotes: 1

Views: 97

Answers (1)

If you want to write a multi-line declaration in GHCi, you need to wrap it in :{ :} so that Haskell knows to evaluate the whole definition at the same time. What you're doing right now is defining a function fib where fib 0 is 1, then defining a new function fib that shadows the first one where fib 1 is 1, and then defining a third function shadowing the second one, which is the only definitition that Haskell sees when it tries to execute fib 3. The solution is to tell GHCi that this is all the same definition, which is done using the :{ command:

Prelude> :{
Prelude| fib 0 = 1
Prelude| fib 1 = 1
Prelude| fib n = fib (n - 1) + fib (n - 2)
Prelude| :}
Prelude> fib 3
3

It's worth noting that implementing fib as a recursive function like this is bound to be time-inefficient, and it's generally better to define it as a recursive infinite list, like this:

Prelude> :{
Prelude| fib n = fibs !! n
Prelude|    where fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
Prelude| :}
Prelude> fib 3
3

Upvotes: 5

Related Questions