Beginner question: Examples don't work for me :/

Hi. I am very new to Haskell and I am stucked on this page: Syntax in Functions - Learn You a Haskell for Great Good!

None of the examples works for me. For example I get:

GHCi, version 8.10.7:  :? for help
Prelude> lucky 7 = "LUCKY NUMBER SEVEN!"
Prelude> lucky x = "Sorry, you're out of luck, pal!"
Prelude> lucky 7
"Sorry, you're out of luck, pal!"

What do I do wrong?

You are redefining lucky on line 2, because you are in GHCI. GHCI is an interactive interpreter, but the examples in the textbook are expected to be run in a text file. Your two options are:

  1. set up a cabal project (I expect this will be outlined in the textbook introduction)
  2. use multiline GHCI inputs, which are input with the :{ herald I believe. So if you type :{ and then type in the definition of lucky it should work (you close a multiline GHCI input with :} or }: I believe)

You do not need to set up a cabal project to use a text file as input to GHC. You need only write the text file, and pass it directly to GHC or GHCi.

Cabal solves the problem of making sure the right packages are installed with the right versions when you build your software project. This will become important when you build projects, but it’s not something you need to worry about when just trying out examples like this. So go ahead and put your simple example code in a file, like Test.hs or something like that, and run ghci Test.hs to try it out. If you edit the file, you can use :r to reload the source code.


I strongly recommend following GHCup’s First Steps tutorial it’s short and covers the most common ways to build your Haskell programs.