Skip to content
LumenaryAcademy
Professional 70 min

Tools, ecosystem and a complete project

How Haskell teams build, format, lint, document and ship code, and a small calculator language built from parser combinators up.

Code tested · 2AI-draftedAwaiting review by a computer scientist
MotivationH

From scripts to projects

Every program in this course so far has been a single file run with runghc. Real software has several modules, depends on libraries, has tests, is built the same way on every machine, and is checked automatically before each change is merged. This lesson covers the tools that make that routine in Haskell, and then puts the whole course together in one project: a small calculator language with variables, written the way an experienced Haskell programmer would write it, from a parser built out of tiny combinators to an evaluator that reports every error without crashing.

ExplanationH

The professional toolchain

Cabal projects

A Cabal package is a directory with a .cabal file that describes its components: libraries, executables and test suites. Running cabal init asks a few questions and writes one for you. A small project might look like this:

text
calc/
  calc.cabal
  app/Main.hs
  src/Calc/Parser.hs
  src/Calc/Eval.hs
  test/Spec.hs

and its .cabal file like this (a fragment):

text
cabal-version:      3.4
name:               calc
version:            0.1.0.0
synopsis:           A small calculator with variables
license:            Apache-2.0
build-type:         Simple

common shared
    default-language: GHC2021
    ghc-options:      -Wall

executable calc
    import:           shared
    main-is:          Main.hs
    hs-source-dirs:   app
    build-depends:    base >=4.18 && <5,
                      containers >=0.6 && <0.9

The common stanza holds settings every component imports: the language edition and -Wall. build-depends lists the packages the code imports, with version bounds. Even containers, which ships with GHC, must be listed here: inside a project, only declared dependencies are visible. (Running single files with runghc, as in this course, sees every package installed with the compiler.)

The commands you will type every day:

CommandWhat it does
cabal buildResolve dependencies (downloading them from Hackage the first time), compile everything.
cabal run calc -- argsBuild and run the executable, passing it arguments.
cabal replOpen GHCi with the project's modules and dependencies loaded.
cabal testBuild and run the test suites.
cabal freezeRecord the exact versions used, for reproducible builds.

Cabal builds in isolation: each project gets exactly the library versions its solver chose, cached and shared safely between projects. The "dependency hell" stories about Haskell date mostly from before this design became the default in Cabal 3.0 (2019).

Stack

Stack reads the same .cabal files (or generates them from a package.yaml), but instead of solving version constraints it pins every dependency to a Stackage snapshot: a set of package versions that the Stackage maintainers have built and tested together. A one-line setting in stack.yaml chooses the snapshot. Teams that value "exactly the same versions everywhere, with no solver surprises" often prefer Stack; teams that want the newest versions or work closely with Hackage often prefer Cabal with a freeze file. Both are fine choices, and both are installed by GHCup.

Editor, formatter, linter

  • Haskell Language Server (HLS) gives any editor that speaks the Language Server Protocol the type of any expression on hover, errors as you type, go-to-definition, renaming, and code actions such as "add missing import" or "fill in the missing pattern cases". Install it with GHCup; it must match your GHC version, which GHCup takes care of.
  • Formatters end debates about layout. Ormolu has one fixed style; Fourmolu is a fork with settings. Most teams run one in CI and in a pre-commit hook.
  • HLint suggests simplifications: concat (map f xs) becomes concatMap f xs, an unnecessary lambda becomes a section, if c then True else False becomes c. It is configurable, and teams switch off the hints they disagree with.
  • -Wall and -Werror in CI. Locally, warnings are hints; in continuous integration, many teams make them errors, so incomplete patterns and unused imports never reach the main branch.

Finding and documenting libraries

Hackage hosts the documentation of every published package, generated by Haddock from comments in the source. A comment starting with -- | documents the declaration below it:

haskell
-- | Evaluate an expression in an environment of variables.
-- Fails with a message for unknown variables and division by zero.
eval :: Env -> Expr -> Either String Double

Hoogle searches all of it, by name or by type. Typing [a] -> Int -> [[a]] finds functions that split a list into chunks; typing (a -> Bool) -> [a] -> ([a], [a]) finds partition and span. Because types say so much in Haskell, searching by type is surprisingly effective, and experienced programmers do it many times a day.

Libraries you will meet in most production codebases: text and bytestring (efficient text and binary data), containers (maps and sets), aeson (JSON), megaparsec (parsing), optparse-applicative (command-line arguments), async and stm (concurrency), mtl (monad transformers), and for web services servant or scotty on top of the warp server.

Worked examplesH

Project: a calculator language

The goal is a program that reads lines such as let price = 250 and price * (1 + rate), keeps variables between lines, respects operator precedence, and reports problems (syntax errors, unknown variables, division by zero) as messages rather than crashes. It has three parts, which in a real project would be three modules: a parser, an evaluator, and a driver.

Step 1: parser combinators

A parser for values of type a is a function that looks at the start of a string and either fails or returns an a together with the remaining input. Wrapped in a newtype, it becomes an instance of the classes from lessons 6 and 7, and those instances are the whole library:

haskell
import Control.Applicative (Alternative (..))
import Data.Char (isDigit, isSpace)

-- A parser consumes the start of a string and, if it succeeds,
-- returns a result together with the rest of the input.
newtype Parser a = Parser {runParser :: String -> Maybe (a, String)}

instance Functor Parser where
  fmap f (Parser p) = Parser $ \s -> case p s of
    Nothing -> Nothing
    Just (a, rest) -> Just (f a, rest)

instance Applicative Parser where
  pure x = Parser $ \s -> Just (x, s)
  Parser pf <*> Parser pa = Parser $ \s -> case pf s of
    Nothing -> Nothing
    Just (f, rest) -> case pa rest of
      Nothing -> Nothing
      Just (a, rest') -> Just (f a, rest')

instance Monad Parser where
  Parser p >>= f = Parser $ \s -> case p s of
    Nothing -> Nothing
    Just (a, rest) -> runParser (f a) rest

-- Alternative: try one parser, and if it fails, another on the same input.
instance Alternative Parser where
  empty = Parser (const Nothing)
  Parser p <|> Parser q = Parser $ \s -> case p s of
    Nothing -> q s
    success -> success

satisfy :: (Char -> Bool) -> Parser Char
satisfy ok = Parser $ \s -> case s of
  c : rest | ok c -> Just (c, rest)
  _ -> Nothing

token :: Parser a -> Parser a
token p = p <* many (satisfy isSpace)

symbol :: Char -> Parser Char
symbol c = token (satisfy (== c))

natural :: Parser Int
natural = token (read <$> some (satisfy isDigit))

sepBy1 :: Parser a -> Parser sep -> Parser [a]
sepBy1 p sep = (:) <$> p <*> many (sep *> p)

main :: IO ()
main = do
  print (runParser natural "2026 and more")
  print (runParser natural "no digits")
  print (runParser (many (symbol 'a')) "a a ab")
  print (runParser (sepBy1 natural (symbol ',')) "3, 1, 4,1 rest")
  print (runParser (symbol '[' *> sepBy1 natural (symbol ',') <* symbol ']') "[10, 20, 30]")
  print (runParser (Left <$> natural <|> Right <$> symbol 'x') "x marks the spot")
text
Just (2026,"and more")
Nothing
Just ("aaa","b")
Just ([3,1,4,1],"rest")
Just ([10,20,30],"")
Just (Right 'x',"marks the spot")

Each instance is a few lines, and each gives a different way to combine parsers:

  • Functor: read <$> some (satisfy isDigit) parses digits and converts the result, leaving the rest of the input alone.
  • Applicative: (:) <$> p <*> many (sep *> p) runs parsers in sequence and combines their results; *> and <* run both but keep only the result on the side the arrow points to. That is how token skips trailing spaces and how the bracketed list ignores its brackets.
  • Monad: >>= lets the next parser depend on what was just parsed. We will need it once, to treat the word let specially.
  • Alternative: p <|> q tries p, and if it fails, tries q on the same input. many p and some p (zero-or-more and one-or-more repetitions) come free with the class.

This design, small parsers combined by ordinary functions, is how parsing is usually done in Haskell. Production code uses megaparsec, which adds precise error messages with positions, but its interface is recognisably the one above.

Step 2: the complete program

haskell
module Main (main) where

import Control.Applicative (Alternative (..))
import Data.Char (isAlpha, isAlphaNum, isDigit, isSpace)
import Data.List (mapAccumL)
import qualified Data.Map.Strict as Map

------------------------------------------------------------------------
-- A small parser combinator library (as in the first example)

newtype Parser a = Parser {runParser :: String -> Maybe (a, String)}

instance Functor Parser where
  fmap f (Parser p) = Parser $ \s -> fmap (\(a, rest) -> (f a, rest)) (p s)

instance Applicative Parser where
  pure x = Parser $ \s -> Just (x, s)
  pf <*> pa = do
    f <- pf
    f <$> pa

instance Monad Parser where
  Parser p >>= f = Parser $ \s -> case p s of
    Nothing -> Nothing
    Just (a, rest) -> runParser (f a) rest

instance Alternative Parser where
  empty = Parser (const Nothing)
  Parser p <|> Parser q = Parser $ \s -> maybe (q s) Just (p s)

satisfy :: (Char -> Bool) -> Parser Char
satisfy ok = Parser $ \s -> case s of
  c : rest | ok c -> Just (c, rest)
  _ -> Nothing

token :: Parser a -> Parser a
token p = p <* many (satisfy isSpace)

symbol :: Char -> Parser Char
symbol c = token (satisfy (== c))

-- p, then any number of (operator, p), combined from the left: 8 - 3 - 2 = (8 - 3) - 2
chainl1 :: Parser a -> Parser (a -> a -> a) -> Parser a
chainl1 p op = p >>= rest
  where
    rest acc = (do f <- op; x <- p; rest (f acc x)) <|> pure acc

------------------------------------------------------------------------
-- The language: syntax tree and grammar

data Op = Add | Sub | Mul | Div | Pow deriving (Eq, Show)

data Expr
  = Num Double
  | Var String
  | Neg Expr
  | BinOp Op Expr Expr
  deriving (Show)

data Statement = Assign String Expr | Eval Expr

number :: Parser Double
number = token $ do
  whole <- some (satisfy isDigit)
  frac <- (satisfy (== '.') *> some (satisfy isDigit)) <|> pure ""
  pure (read (if null frac then whole else whole ++ "." ++ frac))

identifier :: Parser String
identifier = token ((:) <$> satisfy isAlpha <*> many (satisfy isAlphaNum))

operator :: Char -> Op -> Parser (Expr -> Expr -> Expr)
operator c op = BinOp op <$ symbol c

-- expr   = term   (('+' | '-') term)*
-- term   = power  (('*' | '/') power)*
-- power  = unary  ('^' power)?          (right-associative)
-- unary  = '-' unary | atom
-- atom   = number | identifier | '(' expr ')'
expr, term, power, unary, atom :: Parser Expr
expr = term `chainl1` (operator '+' Add <|> operator '-' Sub)
term = power `chainl1` (operator '*' Mul <|> operator '/' Div)
power = do
  base <- unary
  (BinOp Pow base <$> (symbol '^' *> power)) <|> pure base
unary = (Neg <$> (symbol '-' *> unary)) <|> atom
atom = (Num <$> number) <|> (Var <$> identifier) <|> (symbol '(' *> expr <* symbol ')')

statement :: Parser Statement
statement = assignment <|> (Eval <$> expr)
  where
    assignment = do
      keyword <- identifier
      if keyword /= "let"
        then empty
        else Assign <$> identifier <*> (symbol '=' *> expr)

parseStatement :: String -> Either String Statement
parseStatement input = case runParser (many (satisfy isSpace) *> statement) input of
  Just (s, "") -> Right s
  Just (_, rest) -> Left ("unexpected " ++ show rest)
  Nothing -> Left "could not parse the line"

------------------------------------------------------------------------
-- Evaluation

type Env = Map.Map String Double

eval :: Env -> Expr -> Either String Double
eval _ (Num x) = Right x
eval env (Var v) = maybe (Left ("unknown variable " ++ v)) Right (Map.lookup v env)
eval env (Neg e) = negate <$> eval env e
eval env (BinOp op a b) = do
  x <- eval env a
  y <- eval env b
  apply op x y

apply :: Op -> Double -> Double -> Either String Double
apply Div _ 0 = Left "division by zero"
apply op x y = Right (f x y)
  where
    f = case op of
      Add -> (+)
      Sub -> (-)
      Mul -> (*)
      Div -> (/)
      Pow -> (**)

------------------------------------------------------------------------
-- Running a script, one line at a time, threading the variables through

run :: Env -> String -> (Env, String)
run env line = case parseStatement line >>= execute of
  Left err -> (env, "error: " ++ err)
  Right (env', shown) -> (env', shown)
  where
    execute (Assign name e) = do
      v <- eval env e
      pure (Map.insert name v env, name ++ " = " ++ display v)
    execute (Eval e) = do
      v <- eval env e
      pure (env, display v)

display :: Double -> String
display x
  | x == fromInteger r && abs x < 1e15 = show r
  | otherwise = show x
  where
    r = round x

script :: [String]
script =
  [ "1 + 2 * 3",
    "(1 + 2) * 3",
    "2 ^ 3 ^ 2",
    "8 - 3 - 2",
    "let price = 250",
    "let rate = 0.25",
    "price * (1 + rate)",
    "-price / 8",
    "10 / (5 - 5)",
    "width * 2",
    "3 + * 4",
    "let x2 = price / 100",
    "x2 ^ 2"
  ]

main :: IO ()
main = do
  let (finalEnv, outputs) = mapAccumL run Map.empty script
  mapM_ (\(line, out) -> putStrLn (line ++ "  =>  " ++ out)) (zip script outputs)
  putStrLn ("variables: " ++ show (Map.toList finalEnv))
text
1 + 2 * 3  =>  7
(1 + 2) * 3  =>  9
2 ^ 3 ^ 2  =>  512
8 - 3 - 2  =>  3
let price = 250  =>  price = 250
let rate = 0.25  =>  rate = 0.25
price * (1 + rate)  =>  312.5
-price / 8  =>  -31.25
10 / (5 - 5)  =>  error: division by zero
width * 2  =>  error: unknown variable width
3 + * 4  =>  error: unexpected "+ * 4"
let x2 = price / 100  =>  x2 = 2.5
x2 ^ 2  =>  6.25
variables: [("price",250.0),("rate",0.25),("x2",2.5)]

The program compiles without a single warning under -Wall. A walk through its design:

The grammar is the code. The comment above expr gives the grammar, and the five definitions below it are a line-by-line translation. Precedence comes from the layering: an expr is made of terms, so * binds tighter than +. chainl1 makes - and / associate to the left (8 - 3 - 2 is 3, not 7), while power calls itself on its right, so ^ associates to the right (2 ^ 3 ^ 2 is 2⁹ = 512), as in mathematics.

The syntax tree is an algebraic data type. Expr has one constructor per kind of expression, and eval has one equation per constructor, which -Wall checks for completeness. Adding a new operator means adding a constructor to Op and following the compiler's warnings.

Errors are values. Parsing returns Either String Statement, evaluation returns Either String Double, and run chains them with >>=. No exception is thrown anywhere; the line 10 / (5 - 5) produces a message and the script carries on. This is also why the evaluator is trivial to test: it is a pure function from an environment and an expression to a result.

State is threaded, not mutated. mapAccumL walks the script carrying the environment from one line to the next and collecting each line's output: a fold that also produces a list. The environment is a Data.Map.Strict, and each assignment returns a new map, sharing almost all of its structure with the old one.

let uses the monad, once. assignment parses an identifier and then decides, based on what it saw, whether to continue or fail with empty. Because <|> restarts from the same input, statement then falls back to parsing an expression. That dependency on a previous result is exactly what >>= is for; everything else in the parser is applicative.

Where to take it next

Good extensions, in rising order of difficulty: add functions such as sqrt and max (a new constructor Call String [Expr]); add a test suite with properties such as "printing an expression and parsing it back gives the same tree"; switch the parser to megaparsec to get error positions; read lines from standard input with getContents and lines to make it an interactive tool; split it into a library and an executable in a Cabal project.

History & global context

Where Haskell is used

Haskell is a small language by number of users, and it is honest to say so: there are fewer jobs, fewer libraries and fewer Stack Overflow answers than for Python or Java. It is also used in production by companies that chose it deliberately, mostly where correctness matters a lot and a small, strong team maintains a complex system for years:

  • Finance: banks and trading firms (Standard Chartered has used a Haskell dialect of its own for many years) and fintech companies such as Mercury.
  • Blockchain: the Cardano node and its smart-contract tooling are written in Haskell.
  • Developer tools: Pandoc, the universal document converter; ShellCheck, the shell-script linter; the PostgREST server; the Hasura engine started in Haskell.
  • Compilers and languages: GHC itself, Elm's compiler, PureScript's compiler, the Agda proof assistant, and many research and industrial language tools.
  • Large-scale rule engines: Meta has described using Haskell, through its Haxl library, for Sigma, the system that fights spam and abuse.

Even more widely, Haskell is a language people learn to become better programmers in other languages. Algebraic data types, type classes, Maybe-style optional values, monadic error handling, property-based testing and immutable-by-default data have spread from Haskell into nearly every modern language; having seen them in their original form, you will recognise them everywhere.

Common misconceptionsH

Common misconceptions

Misconception

"Haskell projects are stuck in dependency hell." That reputation comes from older versions of Cabal, which installed every library into one shared database where versions clashed. Since Cabal 3.0, builds are isolated per project and libraries are cached by exact version, and Stack's snapshots offer a second, curated route. Version conflicts still happen occasionally, as in every ecosystem, but they are rarely worse than elsewhere.

Misconception

"I must master monad transformers and type-level programming before writing real Haskell." Most production Haskell is ordinary functions, algebraic data types, Maybe, Either, records and a thin layer of IO, exactly the subset this course teaches. Advanced type features exist and are useful in libraries, but many experienced teams deliberately keep application code simple, a style sometimes called "simple Haskell" or "boring Haskell".

Misconception

"Parser combinators are a toy; real parsers need a generator." Combinator libraries such as megaparsec parse programming languages, configuration formats and network protocols in production, and the Happy and Alex tools (Haskell's equivalents of yacc and lex) exist for the cases where a grammar-driven generator is a better fit. Both approaches are respected; GHC's own parser uses Happy.

Further reading

Where to go next

  • Keep the GHC User's Guide and Hoogle open while you work.
  • The Typeclassopedia goes further into Foldable, Traversable, Applicative and Monad, and their laws.
  • Simon Marlow's Parallel and Concurrent Programming in Haskell is the reference for the topics of lesson 9.
  • haskell.org's documentation page lists books, courses and tutorials, free and paid, for every level.
  • Ask questions on Haskell Discourse; the community is welcoming to beginners.
  • Read real code: Pandoc and ShellCheck are large, mature and well organised. Hackage links to every package's source.
Exercises

Exercises

1. Tools, ecosystem and a complete project

Warm-upHuman

Your Cabal project's Main.hs adds import qualified Data.Map.Strict as Map, and cabal build now fails, saying it cannot find the module. containers ships with GHC. What is the fix?

Choose one

2. Tools, ecosystem and a complete project

CoreHuman

What does Stack do differently from Cabal when choosing the versions of a project's dependencies?

Choose one

3. Tools, ecosystem and a complete project

Warm-upComputational

Using the calculator from the lesson, what number does it print for the line 2 * 3 ^ 2?

4. Tools, ecosystem and a complete project

StretchComputational

Using the calculator from the lesson, what number does it print for the line -2 ^ 2? (In ordinary mathematical notation, −2² means −(2²) = −4.)

5. Tools, ecosystem and a complete project

CoreComputational

Using the calculator from the lesson, what does it print after => for the line letter + 1, run on an empty set of variables? Give the whole message.

6. Tools, ecosystem and a complete project

CoreHuman

Which instance gives the Parser type the functions many and some, and the operator <|>?

Choose one

Further reading and resources

  • Cabal user guideEverything about .cabal files, cabal.project and the cabal commands.
  • The Haskell Tool StackStack's documentation, including how snapshots work.
  • StackageCurated snapshots of Hackage packages known to build together.
  • Haskell Language ServerEditor support for VS Code, Neovim, Emacs and others.
  • HLintThe standard linter, suggesting simpler and more idiomatic code.
  • OrmoluA formatter with a single, fixed style; Fourmolu is its configurable fork.
  • HaddockThe documentation generator used for every package on Hackage.
  • The megaparsec packageThe parser combinator library most production code uses, with good error messages.
  • Haskell DiscourseThe community's main discussion forum.