Skip to content

Instantly share code, notes, and snippets.

@domgetter
Last active February 6, 2016 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domgetter/015f48c990adff85958a to your computer and use it in GitHub Desktop.
Save domgetter/015f48c990adff85958a to your computer and use it in GitHub Desktop.
class Maybe
def initialize(value)
@value = value
end
def map(&block)
Maybe.new(bind &block)
end
def bind
if @value.nil?
Maybe.new(nil)
else
yield @value
end
end
end
class Array
def for(*m_acc, &block)
if self.count > 1
first.bind {|v| self[1..-1].for(*(m_acc + [v]), &block) }
else
first.map {|v| block.call(*(m_acc + [v])) }
end
end
end
module Kernel
def Maybe(v)
Maybe.new(v)
end
end
mx, my, mz = Maybe(1), Maybe(2), Maybe(3)
[mx, my, mz].for {|x, y, z| x + y + z }
#=> #<Maybe @value=6>
[mx, Maybe(nil), mz].for {|x, y, z| x + y + z }
#=> #<Maybe @value=nil>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment