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. 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):
:load add.hs[1 of 1] Compiling Main ( add.hs, interpreted ) Ok, modules loaded: Main.
add 1 23
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:
Alternatively, you can provide the path
to your Haskell source file as the argument to
:load. This path can be either absolute ...