Skip to content

Instantly share code, notes, and snippets.

@tuscen
Last active August 29, 2015 14:27
Show Gist options
  • Save tuscen/eaf06d6fccfd449e037f to your computer and use it in GitHub Desktop.
Save tuscen/eaf06d6fccfd449e037f to your computer and use it in GitHub Desktop.
Ruby implementation of something that looks like maybe monad.
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