I am running the GHCi console, and typing
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
and then
fib 5
and the console hangs and dies with:
: Out of memory
What am I doing wrong ?
By typing the declarations separately into ghci, each one is read as a separate definition of fib
, shadowing its predecessors. In other words, you're effectively running
fib n = fib (n-1) + fib (n-2)
fib 5 -- infinite recursion here
The easiest way to avoid this problem is to put the definition of fib
into a file.
At the console, you haven't defined a single function fib
with 3 different cases; you first defined fib 0 = 0
, then overwrite that with a new function fib 1 = 1
, then finally with a third function fib n = fib (n-1) + fib (n-2)
that has no base case. You can use
> fib 0 = 1; fib 1 = 1; fib n = fib (n-1) + fib (n-2)
to correctly define a single, 3-case function.
Note this is primarily a problem starting with GHCi 8, since in previous versions you would have to use let
to start the definition and would get a parse error on the second line:
> let fib 0 = 0
> fib 1 = 1
<interactive>:3:7: parse error on input '='