I'm learning Haskell, and am having trouble with a basic factorial function from this tutorial.
Basically, I've defined a factorial as such:
Prelude> let factorial 0 = 1
Prelude> let factorial n = n * factorial (n - 1)
The type checks out:
Prelude> :t factorial
factorial :: Num a => a -> a
which makes sense. However, the behavior of this function doesn't. It results in (interactive): out of memory
no matter what the input is.
Prelude> factorial 5
(interactive): out of memory
I have to assume this is an infinite recursive call leading to an out of memory error, but I'm not sure what could possibly be causing it. The same thing happens with factorial 0
, even though I've explicitly declared this to be 1:
Prelude> factorial 0
(interactive): out of memory
Now, here's the weird part: If I define the factorial function in a file, it works fine. I create a file tesths.hs
s.t.:
factorial 0 = 1
factorial n = n * factorial (n - 1)
Then, if I go back to GHCI and run :l tesths.hs
, I can execute factorial 5
without error.
What's going on here?
Two functions were defined, rather than a single function with two cases. Try the same commands having first run :set -Wall
, and you should get a name shadowing warning. To solve the problem, try
let factorial 0 = 1; factorial n = n * factorial (n - 1)
instead.