Groovy web console

subscribe to the feed Subscribe
to this
The MayBe monad, Groovy style (via #groovywebconsole)
tweet this snippet Tweet

The MayBe monad, Groovy style

Published 8 years ago by Dierk König with tags monad maybe null-safe
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
class MayBe<Subject> {
    final Subject val
    MayBe(Subject val){ this.val = val }

    MayBe bind ( MayBe arg, Closure combine ) {
        if (arg.val == null) return arg
        if (val     == null) return this
        return new MayBe(combine(val, arg.val))

def (one, two, three, nil) = [1,2,3,null].collect{ new MayBe(it) }

assert 9 == one
    .bind(two)   {a,b -> a + b}
    .bind(three) {a,b -> a * b}

assert null == one
    .bind(two)   {a,b -> a + b}
    .bind(nil)   {a,b -> throw RuntimeException("should not execute")}
    .bind(three) {a,b -> a * b}

println "done"