Skip to content

Instantly share code, notes, and snippets.

@SiestaMadokaist
Created August 31, 2015 08:02
Show Gist options
  • Save SiestaMadokaist/0c48957bb7cfd526acba to your computer and use it in GitHub Desktop.
Save SiestaMadokaist/0c48957bb7cfd526acba to your computer and use it in GitHub Desktop.
simple maybe monad example.
class Just
def initialize(value)
@value = value
end
def map(methodsymbol=nil, *args, &block)
if((not methodsymbol.nil?) and block_given?)
raise BlockMethod, "argument should be either methodsymbol, or block process"
end
if(block_given?)
result = block.call(self.value) || Nothing
else
begin
result = self.value.send(methodsymbol, *args)
rescue NoMethodError
result = Nothing
end
end
Maybe.from_value(result)
end
def ==(other)
(@value == other.value) && (other.class == Just)
end
def value(anything = nil)
@value
end
end
class Nothing
def self.map(methodsymbol=nil, *args, &block)
self
end
def self.is?(something)
return self == something
end
def self.value(default = nil)
default
end
end
class Maybe
def self.from_value(value)
if(value.nil? || Nothing.is?(value))
return Nothing
else
return Just.new(value)
end
end
end
baz = Maybe.from_value({foo: "bar"})
a = baz.map{|x| x[:foo]}
# Just(@value="bar")
b = baz.map{|x| x[:foo]}.map{|x| x.upcase}
# Just(@value="BAR")
c = baz.map{|x| x[:bar]}
# Nothing
d = baz.map{|x| x[:bar]}.map{|x| x[:foo]}
# Nothing
# lastly, take the value
a.value == "bar"
b.value == "BAR"
c.value == nil
d.value = nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment