Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Monads 101 with C++

Denis Kormalev
Las Vegas, NV, 2018
Functors
©Aditya Bhargava
Functor operations
• Type constructor
• unit
• map (or fmap in Haskell )
Functor laws
• Identity:
• x.map(Identity) === x
• Composition:
• x.map(A).map(B) === x.map(AandB)
Monads
©Aditya Bhargava
Monad operations
• Type constructor
• unit
• flatMap (or bind in Haskell)
• Monad is usually a functor
Monad laws
• Left identity:
• Monad.unit(x).flatMap(A) === A(x)
• Right identity:
• x.flatMap(Monad.unit) === x
• Associativity:
• x.flatMap(A).flatMap(B) === x.flatMap(xx -> A(xx).flatMap(B))
Option monad
Either monad
Not really a monad, but we can alter it a bit to be one
List monad
Other useful monads
• Eval
• Delays calculation and trampolines its flatMaps
• Future
• Represents value that will be accessible at some future point of timeline
• Reader
• Carries value through morphisms (e.g. configuration)
• Writer
• Returns some additional data with the answer (e.g. logging)
• State
• Combination of Reader and Writer, carries data through morphisms and
allows to change it
Referential transparency
Monad transformers
Other useful morphisms at OptionT
• Option<T> -> Option<NewT>
• Option<T> -> M<Option<NewT>>
• M<?> -> NewM<?>
Questions?

You might also like