On Github AshtonKem / monads
Ashton Kemerling
Pivotal Labs Employee (Tracker)
Professional polyglot, hobbyist Clojure/Haskell user
Oh hey, these are some notes. They'll be hidden in your presentation, but you can see them if you open the speaker notes window (hit 's' on your keyboard).Haskell is a ML based language
It is functional (purely)
No objects
Parenthesis Not Required
Functions can be defined infix (2 arguments only) or prefix
Symbols can be functions too, like >>= and $
Every type has 1 signature, 1 or more constructor
Type and Constructor exported separately
Data Bool = True | False
Data Maybe a = Nothing | Just a
A bit like Interfaces
Used for type based method dispatch
Also used to restrict types a function will accept
class Eq a where (==), (/=) :: a -> a -> Bool x /= y = not (x == y) x == y = not (x /= y)
Mathematical Concept
A common way of chaining computations together
A borrowed term from Philosophy
A monad is a data type with the following functions
Takes a non-monadic value, turns it into one in the simplest way
Unrelated to the return statement in imperative languages
Accepts two arguments, a monadic value and a function
The function must normally accept a non-monadic value, and return a Monad
Bind chains them together
Internal details of monad may be hidden from caller (IO)
Null values are handled with the Maybe type
Compiler requires that null be checked every time we want a maybe value
Results in this mess
routine = case landLeft 1 (0,0) of Nothing -> Nothing Just pole1 -> case landRight 4 pole1 of Nothing -> Nothing Just pole2 -> case landLeft 2 pole2 of Nothing -> Nothing Just pole3 -> landLeft 1 pole3
Gives us these functions
routine = return (0,0) >>= landLeft 1 >>= landRight 4 >>= landLeft 2 >>= LandLeft 1
Shorthand for using >>= manually
Looks a bit like imperative programming
routine = do start <- return (0,0) first <- landLeft 2 start second <- landRight 2 first landLeft 1 second
Used for list comprehensions
[3,4,5] >>= \x -> [x,-x]
[y | x <- [1, 2, 3, 4], y <- [x, -x]]
For chaining stateful computations functionally
Works by passing state into and out of fuctions
Very testable, since each computation stands alone
Example too in depth for 5 minute talk
For logging changes alongside your computation
Very helpful for calculating deltas, or logging
For passing a shared (immutable) environment into a computation
Commonly used for configuration
Thread safe mutable storage
Database-like transactions for in-memory data
Monad libraries aren't unique to functional languages
They are a very good pattern for some types of computation
Once understood, they make a really good library interface
They all follow simple but important rules
Easier to analyze and test automatically
Code examples borrowed (legally) from Learn You a Haskell
www.learnyouahaskell.com