Skip to content

Instantly share code, notes, and snippets.

@zekriad

zekriad/maybe.rb Secret

Last active February 22, 2018 13:10
Show Gist options
  • Save zekriad/a50c6913fc24bba81a7a to your computer and use it in GitHub Desktop.
Save zekriad/a50c6913fc24bba81a7a to your computer and use it in GitHub Desktop.
Ruby Maybe
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