Created
January 8, 2014 14:13
-
-
Save long-long-float/8317283 to your computer and use it in GitHub Desktop.
Maybe monad in ruby
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 value | |
end | |
end | |
class Just < Maybe | |
attr_reader :value | |
def initialize(value) | |
@value = value | |
end | |
def method_missing(name, *args) | |
ret = @value.send(name, *args) | |
ret != nil ? just(ret) : nothing | |
end | |
def ==(other) | |
other.class != Nothing && @value == other.value | |
end | |
def to_s | |
"Just #{@value}" | |
end | |
end | |
class Nothing < Maybe | |
def value | |
nil | |
end | |
def method_missing(name, *args) | |
nothing | |
end | |
def ==(_) | |
false | |
end | |
def to_s | |
'Nothing' | |
end | |
end | |
def just(value) | |
Just.new value | |
end | |
def nothing | |
Nothing.new | |
end | |
#monad laws | |
#1 | |
just('hello').upcase == just('hello'.upcase) | |
#2 | |
just(just(10).value) == just(10) | |
#3 | |
just('Hello').upcase.downcase == just('hello'.upcase).downcase |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment