O'Reilly logo

Real World Haskell by Donald Bruce Stewart, Bryan O'Sullivan, John Goerzen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Haskell Source Files, and Writing Simple Functions

Now that we know how to apply functions, it’s time we turned our attention to writing them. While we can write functions in ghci, it’s not a good environment for this. It accepts only a highly restricted subset of Haskell—most importantly, the syntax it uses for defining functions is not the same as we use in a Haskell source file.[5] Instead, we’ll finally break down and create a source file.

Haskell source files are usually identified with a suffix of .hs. A simple function definition is to open up a file named add.hs and add these contents to it:

-- file: ch03/add.hs
add a b = a + b

On the lefthand side of the = is the name of the function, followed by the arguments to the function. On the righthand side is the body of the function. With our source file saved, we can load it into ghci, and use our new add function straightaway (the prompt that ghci displays will change after you load your file):

ghci> :load add.hs
[1 of 1] Compiling Main             ( add.hs, interpreted )
Ok, modules loaded: Main.
ghci> add 1 2
3

What if ghci cannot find your source file?

When you run ghci, it may not be able to find your source file. It will search for source files in whatever directory it was run. If this is not the directory that your source file is actually in, you can use ghci’s :cd command to change its working directory:

ghci> :cd /tmp

Alternatively, you can provide the path to your Haskell source file as the argument to :load. This path can be either absolute ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required