Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 57 ยท Advanced types

Effect Systems and Free Monads

Understand how Haskell separates what a program does from how it runs: tagless final, free monads, and effect libraries, with a runnable JavaScript stand-in.

A function with type IO () can do anything: read files, call the network, delete a database. That freedom is convenient and also makes code hard to test, because you cannot run it without the real world. Effect systems fix this by splitting a program into two parts: a description of what should happen, and an interpreter that decides how it happens.

This lesson shows three popular answers in increasing order of machinery: plain type classes ("tagless final"), free monads, and modern effect libraries. You need to be comfortable with monads and custom type classes.

Real Haskell is not installed on this site, so Haskell blocks are read-only. The runnable examples are JavaScript stand-ins that show the shape of the idea.

The problem: IO everywhere

Imagine a small greeting program:

HASKELL
greet :: IO ()
greet = do
  putStrLn "Name?"
  name <- getLine
  putStrLn ("Hello, " ++ name)

To test it you must type into a terminal. The logic ("ask, then greet") is tangled with the mechanism (the real console). If the program only described the steps, a test could run the description against fake input and collect the output as a list.

Tagless final: a type class as the interface

The most lightweight approach is to write the program against a type class that lists the operations it needs, and abstract over the monad:

HASKELL
class Monad m => MonadConsole m where
  say :: String -> m ()
  ask :: m String

greet :: MonadConsole m => m ()
greet = do
  say "Name?"
  name <- ask
  say ("Hello, " ++ name)

greet says nothing about how say and ask work, only that they exist. You then provide instances:

HASKELL
instance MonadConsole IO where
  say = putStrLn
  ask = getLine

For tests you write a pure instance, for example on a State monad that holds a list of pending inputs and a log of outputs. The program is untouched. This style is called tagless final because there are no data constructors (tags) describing the program: the program is the polymorphic function.

Describe first, run later

Program Says what to do.
Interpreter Decides how to do it.

Swap the interpreter and the same program runs anywhere.

1 / 2

The free monad idea

A free monad takes the "program as data" idea literally. You define your operations as a plain data type, then wrap it so that any functor becomes a monad for free:

HASKELL
data Free f a
  = Pure a
  | Free (f (Free f a))

instance Functor f => Monad (Free f) where
  Pure a  >>= k = k a
  Free fa >>= k = Free (fmap (>>= k) fa)

Pure means "finished with this value". Free means "perform this instruction, and here is what to do next". Each instruction stores its own continuation. Bind simply pushes the rest of the program into the continuation of every instruction.

Your console operations become a functor:

HASKELL
data ConsoleF next
  = Say String next
  | Ask (String -> next)
  deriving Functor

type Console = Free ConsoleF

say :: String -> Console ()
say s = Free (Say s (Pure ()))

ask :: Console String
ask = Free (Ask Pure)

With those, do notation works on Console exactly as on IO. The result of greet is a value: a tree of Say and Ask nodes that you can inspect, print, optimise or run. An interpreter is a recursive function that walks the tree:

HASKELL
runIO :: Console a -> IO a
runIO (Pure a)            = pure a
runIO (Free (Say s next)) = putStrLn s >> runIO next
runIO (Free (Ask k))      = getLine >>= runIO . k

Writing a second interpreter that reads from a list and collects output is just another recursive function.

A runnable stand-in

JavaScript has no do notation, so the stand-in builds the tree with a small bind. Real Haskell gets Functor, Monad and do from the type system and Free from a library; here we write the same shapes by hand.

JS A program as data, two interpreters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same greet tree is run two different ways. The second interpreter never prints anything: it only analyses the program. That is something IO can never offer, because an IO action is opaque.

Free monads versus tagless final

Both give you testability. They differ in trade-offs:

  • Tagless final is usually faster, because the compiler can specialise the type class away. It has little boilerplate. You cannot inspect the program, though, only run it.
  • Free monads let you inspect, rewrite and serialise a program, and run it with several interpreters. Naive free monads can be slow, and defining the functor and smart constructors is boilerplate.

Many teams choose tagless final, or a mix: a record of functions passed around (the "handle pattern"), which needs no type-class tricks at all.

HASKELL
data ConsoleHandle = ConsoleHandle
  { hSay :: String -> IO ()
  , hAsk :: IO String
  }

Modern effect libraries

Hand-written free monads do not combine well: two effects such as Console and Logger need a way to mix. Several libraries solve this, each with a different design:

  • mtl classes such as MonadState and MonadReader are tagless final in disguise (see State, Reader, Writer and Monad Transformers).
  • polysemy and fused-effects are effect libraries with the program-as-data feel; you list effects in a type-level list such as Sem '[Console, Logger] a, and interpret them one at a time.
  • effectful and bluefin use a ReaderT IO core for speed and keep a similar interface.

The shared pattern is: declare an effect, write a program that uses it, then supply interpreters at the edge of the application.

HASKELL
-- polysemy-style sketch (read-only)
program :: Members '[Console, Logger] r => Sem r ()
program = do
  say "Name?"
  name <- ask
  logInfo ("greeted " <> name)

Library APIs in this area change quickly. Treat the snippets here as the shape of the idea and check the current documentation of the library you choose.

When to use all this

For a small script, plain IO is fine. Reach for effect abstractions when you want fast tests without mocks, several implementations (real, fake, logging), or strict control over what each part of a large program may do. Start with a handle record or a small type class, and move to a library only when the need is clear.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main goal of an effect system?

    By separating description and interpretation, you can run the same program against real or fake implementations.
  2. 2. In tagless final style, how is the program written?

    The program uses a class such as MonadConsole m and never mentions a concrete monad, so any instance can run it.
  3. 3. What does the Pure constructor of Free represent?

    Pure a is the end of the tree: nothing more to do, result a.
  4. 4. What can a free monad do that a tagless final program cannot easily do?

    Because a free monad program is data, you can walk it, count steps, optimise it or serialise it.

Summary

  • IO mixes logic with real-world mechanism; effect abstractions separate them.
  • Tagless final writes programs against a type class and picks an instance later.
  • A free monad stores a program as a tree (Pure or Free) that interpreters walk.
  • Free monads allow inspection; tagless final is usually faster and lighter.
  • Libraries such as polysemy, fused-effects and effectful package these ideas, and mtl is tagless final in practice.
  • Start simple: a handle record or a small class is often enough.

Next: Concurrency and Software Transactional Memory.