Strange Loops

No Matter Where You Go, There You Are

Ruby Monads

| Comments

Inspired by this moonbase entry…

It would have been nice to just specify bind(f) but that didn’t seem to work as ruby parameters appear to be strictly evaluated.

irb(main):001:0> require 'monad'=> trueirb(main):002:0> def f(x); x + 1; end => nilirb(main):003:0> IdentityMonad.wrap(1).bind(method(:f)).bind{|x| x + 2}.value=> 4irb(main):004:0> 

class IdentityMonad
attr_reader :value
def initialize(value)
@value = value
end
def IdentityMonad::wrap(value)
new(value)
end
def pass
yield @value
end
def bind(p=nil,&blk)
if block_given?
IdentityMonad::wrap(blk.call(@value))
else
IdentityMonad::wrap(p.call(@value))
end
end
end