Just trying to do Exercise 3.7 (p. 31) of Hal Daumé III's YAHT manual, I tried to define the Fibonacci function:
fibo 1 = 1
fibo 2 = 1
fibo n = fibo(n-1) + fibo(n-2)
I then requested
fibo(3)
and got:
*** Exception: stack overflow
When I looked into the solution of the exercise I found exactly the same code (with the difference that the function is called fib instead of fibo). What am I doing wrong?
(The manual is from 2006, maybe the language has changed inbetween?) (It is ironic that I ask stackoverflow for a problem of stack overflow…)
This is likely the result of defining the function in ghci
one line at a time. This means that you first define a function fibo 1 = 1
. Then you define another function with the name fibo
(with fibo 2 = 2
) that is scoped more locally, and finally you define a third function named fibo
.
You can wrap multi-line functions between :{
and :}
, and thus define one function fibo
that consists out of three clauses:
Prelude> :{
Prelude| fibo 1 = 1
Prelude| fibo 2 = 1
Prelude| fibo n = fibo (n-1) + fibo (n-2)
Prelude| :}
Prelude> fibo 3
2