Last active
August 29, 2015 14:27
-
-
Save tuscen/eaf06d6fccfd449e037f to your computer and use it in GitHub Desktop.
Ruby implementation of something that looks like maybe monad.
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 Nothing | |
def >> fn | |
self | |
end | |
def value | |
nil | |
end | |
end | |
class Some | |
def initialize value | |
@value = value | |
end | |
def >> fn | |
unit(fn.call(@value)) | |
end | |
def value | |
@value | |
end | |
protected | |
def unit v | |
Maybe.new(v) | |
end | |
end | |
class Maybe | |
def self.new value | |
if value | |
Some.new(value) | |
else | |
Nothing.new | |
end | |
end | |
end | |
def get_value maybe | |
maybe.value | |
end | |
result0 = Maybe.new(10) >> ->(x) { x * 5 } >> ->(x) { x % 20 } | |
result1 = Maybe.new(nil) >> ->(x) { x * 5 } >> ->(x) { x % 20 } | |
puts get_value(result0) # => 10 | |
puts get_value(result1) # => nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment