Skip to content

Instantly share code, notes, and snippets.

@mudge
Last active October 2, 2015 20:27
Show Gist options
  • Save mudge/edc8f4313010727aab78 to your computer and use it in GitHub Desktop.
Save mudge/edc8f4313010727aab78 to your computer and use it in GitHub Desktop.
Implementing Enumerable to simulate Monads
class Maybe
include Enumerable
def initialize(value)
@value = value
end
def each
yield value unless value.nil?
end
attr_reader :value
end
a = Maybe.new('foo')
a.map { |x| "Alice says '#{x}'" }
#=> ["Alice says 'foo'"]
b = Maybe.new(nil)
b.map { |x| "Alice says '#{x}'" }
#=> []
c = Maybe.new(4)
c.select(&:even?)
#=> [4]
c.select(&:odd?)
#=> []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment