22

I thought this would produce a factorial function...

(within ghci)

Prelude> let ft 0 = 1
Prelude> let ft n = n * ft (n - 1)
Prelude> ft 5

(hangs indefinitely, until ^C).

1 Answer 1

32

The two separate let statements are interpreted independently from each other. First a function ft 0 = 1 is defined, and then a new function ft n = n * ft (n - 1) is defined, overwriting the first definition.

To define one function with two cases you have to put both cases into a single let statement. To do this in a single line at the GHCI prompt you can separate the two cases by ;:

Prelude> let ft 0 = 1; ft n = n * ft (n - 1)
Prelude> ft 5
120
Sign up to request clarification or add additional context in comments.

1 Comment

In other words, what you wrote is (almost) correct Haskell; the problem is that GHCI accepts different syntax from what you'd put in a separate source file. If you put those two lines, but without the word let (that's the "almost"), in a file Factorial.hs, then in GHCI enter: :load Factorial then ft 5 you'll get 120. Don't know if you've come across "do notation" yet (e.g. for I/O), but the syntax that's allowed at the GHCI prompt is the same as what's allowed inside a do block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.