Last active
October 2, 2015 20:27
-
-
Save mudge/edc8f4313010727aab78 to your computer and use it in GitHub Desktop.
Implementing Enumerable to simulate Monads
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 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