Basic Structure of a Haskell Program

A Haskell program’s structure is surprisingly simple. You have a main function which does IO, and that’s about it. So the basics:

module Main where

addition a b = a + b

main :: IO ()
main = do let z = addition 5 3
          putStrLn $ "The result is: " ++ show z

Now you can compile this into a simple program using something like:

ghc --make Main.hs -o program

and it should produce an executable called program.

In general, programs are structured as mostly pure functions doing the actual computation coupled with discrete parts of the code dealing with the IO. (There are of course exceptions to this, but the general idea of writing as much pure code as possible is fairly universal.)

Since almost everything is expressed as a bunch of pure functions, you do not pass variables between them–the functions communicate by passing arguments.

The part of your code that does IO is anchored in main. In most cases, all your IO is going to go through main; even if you write IO actions separately and give them names, they will ultimately be executed starting from main.

A “function group” in Haskell is called a “module”. You can have multiple modules, each in its own file:

module Blarg (exportedFunction) where

helper a b = ... -- this will *not* be exported
exportedFunction a b = helper a b -- this *will* be exported

Only the identifiers in the parentheses will actually be exported; the rest are hidden. If you do not include the parentheses at all, everything will be exported by default.

Save this file as Blarg.hs. Now you can import it in Main:

import Blarg

Another useful way to group functions is where:

complicatedFunction a b c = helper 0
  where helper count = ...

This way helper is only in scope for complicatedFunction and also has access to a, b and c from complicatedFunction.

Leave a Comment