Last active
February 6, 2016 02:15
-
-
Save domgetter/015f48c990adff85958a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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