-
-
Save zekriad/a50c6913fc24bba81a7a to your computer and use it in GitHub Desktop.
Ruby Maybe
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
module Monad | |
def lift(&blk) | |
v = bind { |value| blk.call(value) } | |
self.class.unit(v) | |
end | |
def liftM2(m, &blk) | |
lift do |val1| | |
m.bind do |val2| | |
blk.call(val1, val2) | |
end | |
end | |
end | |
def method_missing(method, *args, &block) | |
lift { |value| value.public_send(method, *args, &block) } | |
end | |
def respond_to?(msg_id, priv = false) | |
lift { |value| value.respond_to?(msg_id, priv) } | |
end | |
end | |
class Maybe | |
include Monad | |
attr_reader :value | |
def self.unit(value = nil) | |
new(value) | |
end | |
def initialize(value) | |
@value = value | |
end | |
def bind(&blk) | |
blk.call(@value) unless @value.nil? | |
end | |
end | |
def Maybe(value = nil) | |
Maybe.unit(value) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment