Groovy web console

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

The MayBe monad, Groovy style

Published 4 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}
    .val 

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

println "done"