Groovy Monads

Preview:

Citation preview

Marcin Gryszko@mgryszko

Yet another presentation on MONADS

why am I doing this?

according to Brian Marick…http://www.vimeo.com/20717301

There is an ancient Mayan profecy that states that some day every single human on earth will have done a tutorial about monads and on that point the purpose of the universe will have been achieved and all humans will ascent to paradise

I’ll try to do my bit so that humanity can reach

nirvana

origins

XVIII century

Gottfried

1714 Monadologie

eternal indecomposable

individualhierarchical and aggregatedautonomic and independent

can change itself according to some intrinsic lawsinfinite

space, time matter, and motion are phenomenal

atomhuman being

soulgod – first monad

ultimate elements of the universe

XX century

category theory

abstract view of mathematical concepts

(which are already quite abstract )

categories have:objects

morphisms or maps or arrows

see a relationship withclasses, objects and

methods?

defines monad

how it is related to functional programming?

functional programmin

g

what are monads?

containers

generalized interface for sequential computations

pattern for transmitting state using functions

without mutation

what defines a monad?

monadic type Mjava.util.List

unit operationvalue -> monadconstructor/factory method[1, 2, 3] (Integer -> List<Integer>)

bind operationmonad -> next monad, exposing its internal value for a transformation functionany method in Groovy taking a closure as param[1, 2, 3].bind({ x -> [x, x + 1] }) == [1, 2, 2, 3, 3, 4]

what does bind?(typically)

Take a function and apply it to all values inside the monadEach invocation returns monad M<U>def intermediateMonads = collect { x -> f(x) }Extract U values from all intermediate M<U> monads and assemble the final M<U> monadintermediateMonads.flatten()

monadic laws

(or when a monad is a monad)

1. identity m.bind { x -> unit(x) } ≡ m

transforming to unit doesn’t change a monad

2. unitunit(x).bind(f) ≡ f(x)

unit must preserve the value inside the monad

3. associativity

m.bind(f).bind(g) ≡ m.bind{ x -> f(x).bind(g) }

order of monad composition doesn’t matter

monadic zeros

(optional, empty monad)[]

1. binding with zerom.flatMap({ x -> mzero })≡ mzero

2. unitmzero.bind(f) ≡ mzero

3. plusmzero.plus(m) ≡ mm.plus(mzero) ≡ m

examplesListAsMonad

IOStateResult

Thank you!

Recommended