Groovy web console

subscribe to the feed Subscribe
to this
site
canonical Monad impl in Groovy (via #groovywebconsole)
tweet this snippet Tweet
this
script

canonical Monad impl in Groovy

Published 8 years ago by Dierk König with tags monad
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
// groovy example for 
// http://channel9.msdn.com/shows/Going+Deep/Brian-Beckman-Dont-fear-the-Monads/

class M<State> {
    final State state
    M(State state){ this.state = state }

    M bind ( M ga, fb ) { fb(ga.state) }
}

// a -> M<b> example: a is int, b is String
Closure g = { int a -> new M(a.toString()) }

// b -> M<c> example: b is String, c is int
Closure f = { String b -> new M(b.size()) }

// composition f o g
Closure h = { a -> new M(null).bind(g(a),f) }

def mc = h(42) // mc is of type M<c>

assert mc in M
assert 2 == mc.state