Created
August 31, 2015 08:02
-
-
Save SiestaMadokaist/0c48957bb7cfd526acba to your computer and use it in GitHub Desktop.
simple maybe monad example.
This file contains hidden or 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 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