NPRG086: Functions, trees, processes

Monads in functional programming

Tomáš Petříček, 204 (2nd floor)
petricek@d3s.mff.cuni.cz
@tomasp.net
https://tomasp.net

Background

Thinking about monads

Monads in category theory

A monad over a category \(\mathcal{C}\) is a triple \((T, \eta, \mu)\) where
\(T : \mathcal{C} \rightarrow \mathcal{C}~\) is a functor, \(\eta : {Id}_{\mathcal{C}} \rightarrow T\) and
\(\mu : T^2 \rightarrow T\) are natural transformations such that:

\[\begin{array}{l} \mu_{A} \circ T \mu_A = \mu_{A} \circ \mu_{T A} \\ \mu_{A} \circ \eta_{T A} = \mathit{id}_{T A} = \mu_{A} \circ T \eta_{A} \end{array}\]

\[\definecolor{mc}{RGB}{137,64,96} \newcommand{\mbnd}{>\!\hspace{-0.25em}>\!\hspace{-0.27em}=}\]

Monads in programming

A monad is a triple \((M, \mathit{unit}, \mbnd)\) consisting of a type
constructor \(M\) and two operations of the following types:

\[\begin{array}{lcl} \mbnd &::& M x \rightarrow (x\rightarrow M y) \rightarrow M y\\ \mathit{unit} &::& x\rightarrow M x\\ \end{array}\]

These operations must satisfy the following laws:

\[\begin{array}{l} \mathit{unit}~a~\mbnd~f ~=~ f a\\ m~\mbnd~\mathit{unit} ~=~ m\\ (m~\mbnd~f)~\mbnd~g ~=~ m~\mbnd~(\lambda x.f x~\mbnd~g) \end{array}\]

Metaphors

Explaining monads

Monads as a formal entity

Monad is a data type

Data type M a with operations (satisfying monad laws)

Operation return has a type a -> M a
Operation >>= has a type (a -> M b) -> (M a -> M b)

Many examples of monads

  • List a - list of zero or more a values
  • Maybe a - either Just a or Nothing
  • Reader a and State a for managing state...

Monads as containers

Monad is like a box of things

Monads as computations

Monad is like a railway track



Monads as computations

Monad is like a railway track



Monads as computations

Monad is like a railway track



Monads as computations

Monad is like a railway track



Metaphors

Thinking about monads

  • Cognitive view of maths (Lakoff & Núñez)
  • Movement when composing computations
  • Inside/outside when using containers
  • Metaphors criticised as too concrete!
  • Symbol pushing also a metaphor...

Origins

Programming with monads (1985-95)

Functions

Problematic extra behaviour

  • Partiality - function not defined / not terminating
  • Exceptions - computations fail with no result
  • Input/output - interaction with the environment
  • Non-determinism - produce multiple results
  • Parsers - detect patterns in input stream

Two struggles with extra behaviour

Formal semantics

  • Formal model of real-world programming languages
  • Deal with messy aspects of reality

Language design

  • Unify handling of multiple aspects
  • Encode extras in pure languages
  • Most can be encoded already,
    but some cannot (input/output)

Case #2: Lists of successes (Wadler, 1985)

Model extras as lists

  • Failures (one or zero)
  • Backtracking (lazy lists)
  • Parsing (list of matches)

List comprehensions notation

  • Miranda's [ a + b | a <- foo, b <- foo ]
  • Translated to list-processing primitives
    flatMap : a list -> (a -> b list) -> b list
  • Syntax works for many extras!
  • Not recognized as monadic (yet)

Lists and exceptions (Spivey, 1989 & 1990)

Theory of lists (1989)

  • Categorical model of lists & expr trees
  • "monads seem especially promising"

Theory of exceptions (1990)

  • \(\bullet : (\alpha \rightarrow \beta) \rightarrow \textnormal{maybe}~\alpha \rightarrow \textnormal{maybe}~\beta\)
  • \(prop : \textnormal{maybe}~(\textnormal{maybe}~\alpha) \rightarrow \textnormal{maybe}~\alpha\)
  • \(succeed : \alpha \rightarrow \alpha\) [sic]
  • Monad, forming category via Kleisli construction
  • Derive laws of list comprehensions

Kent Applicative Operating System

John Cupitt (Kent, 1988, 1989) 14,000 lines of Miranda code

Refined Simon Thompsons interaction combinators

return : a -> interact a
comp : (a -> interact b) -> (interact a -> interact b)

Based on stream-based input/output model (Landin, 1970s)
Dialogue = [Response] -> [Request] (Haskell 1.2, 1985)

Monadic operations but without reference!

Notions of computation & monads (Moggi, 89-91)

Cites discussion with Martin Hyland at PhD defence
Categorical semantics of computation based on monads

Model

Supercooled liquid?

  • List comprehensions syntax
  • Two ways of expressing monads (bind/join)
  • Links to monads in category theory
  • Definitions of monads for common extras
  • Oxford, Edinburgh, Kent, Glasgow

Comprehending monads

(Wadler, 1990-92)

Monads for design

Examples of monads from Moggi - strictness, parsers, state, exceptions, IO

From list comprehensions to monad comprehensions

Join or "container" model

Applications

Lazy functional IO

Changing world (Wadler, 1990)

An old canard against functional languages is that they cannot change the world:

They do not "naturally" cope with changes of state, such as altering a location in memory, changing a pixel on a display, or sensing when a key is pressed.

Earlier ways of handling IO

Stream-based models

  • [Response]->[Request] function
  • Recursion to manage state
  • Use combinators to compose
  • Haskell 1.2 original model

World-based models

  • Take World and return new World
  • Can be duplicated, used & discarded!

Linear types can change the world

(Wadler, 1990)

Two operations to rule out!

  • dup a = (a, a)
  • kill a = ()

Type system based on ideas from linear logic

Lot to add to Haskell!

Imperative functional programming
(Peyton Jones & Wadler, 1993)

Works thanks to laziness!

  • Type IO a for effectful computations
  • Operation seqIO : IO () -> IO a -> IO a

Monads

Handling input and output

  • Linear types fit research programme!
  • Sound theory, impractical for implementation
  • Monads as an alternative practical solution
  • Unclear what the IO monad denotes
  • Criticisms - is it even a monad??

Not the essence

Metaphors and syntax

Essence of Functional Programming (Wadler, 1992)

Why have regrets about syntax?

Syntax is not the essence of the idea!
Becomes very useful and important in practice...
Not part of the research programme?

Two notations for monads

Comprehensions

Existed before for lists
Used to handle extras!

  [ a + b |
      a <- foo
      b <- bar ]

Generalized but dropped
Monad as container

Monad syntax

Introduced in IO context Launchbury's Gofer (1993)

{ a <- foo;
  b <- bar
  return (a + b) }

Added to Haskell in 96
Monad as computation

SQL comprehensions

Bringing back monad comprehensions

Requires additional operations: groupWith, filter, zipWith, etc.

Practical motivation, no categorical model!

The F# Computation Zoo

Monads

Comprehensions and do notation

  • Essential part of the origins!
  • Comprehensions for containers
  • Do notation for computations
  • Interesting research extensions
  • Syntax seen as spurious design aspect
  • In principle not needed, but...

Challenges

Monadic parsers (or not)

Tempting harmful abstraction?

Parser a reads input string and produces value a

  • Parse one thing and then another thing
    Parser a -> Parser b -> Parser (a * b)

  • Try parsing in two ways, use the first success
    Parser a -> Parser a -> Parser a

Parsers can be extended to support
monadic operations >>= and return.

-- Parse array literal
ints :: Parser [Int]
ints =
 [ n:ns |
    _ <- char ’[’
    n <- int
    ns <- many nint
    _ <- char ’]’]

-- Parse int after comma
nint :: Parser Int
nint =
 [ x |
    _ <- char ’,’
    x <- int ]    

Monadic parsers

Monadic compre­hensions helpful for readability!

Variables n and ns in
scope after bound

Useful for IO and other monads, not much here...

Parsers

Monadic operations

  • Hutton (1989-90) - no monadic bind
  • Wadler (1987) - using flatMap
  • Wadler (1990-92) - monadic bind added
  • Hutton & Meijer (1996) - monadic parsers!
  • Wadler (1997) - far superior style!
  • Swierstra & Duponcheel (1996) - drop bind

Tempting harmful abstraction?

Swierstra & Duponcheel (1996)

The normal disadvantages of conventional [monadic] parsers, such as their lack of speed and their poor error reporting are remedied.

The techniques [do not] extend to monadic parsers. [T]he monadic formulation [causes] the evaluation of the parser construction over and over (...).

Challenges

Composing monadic effects

Monad transformers to effect handlers

  • Composing using monad transformers (1995)
    Layers of effects, lift operations through the stack
  • Transformers break down
    Order fixed early, liftings multiply, catch and callcc hard
  • Algebraic effects, revisiting theory (2001)
    Semantics with effects as operations with equations
  • From exception handlers to effect handlers
    Shift to design, add practically-motivated handlers

Conclusions

Monads in programming

History & philosophy of monads

  • Still dealing with functions...
    How to model or implement extra behaviours?
  • Strong "Algol" research programme
    Language should have a clean formal model!
  • Same structure discovered repeatedly
    Multiple implementations, discoveries in theory
  • Less room for entity evolution?
    Equivalent definitions chosen as needed