Skip to content

Instantly share code, notes, and snippets.

@sescobb27
Forked from guilleiguaran/maybe.rb
Last active September 5, 2015 20:02
Show Gist options
  • Save sescobb27/dd725e33b288111df987 to your computer and use it in GitHub Desktop.
Save sescobb27/dd725e33b288111df987 to your computer and use it in GitHub Desktop.
Maybe Monad
require 'singleton'
class Maybe
def self.unit(value)
if value.nil? || (value.respond_to?(:empty?) && value.empty?)
Nothing.instance
else
Just.new(value)
end
end
end
class Just < Maybe
attr_reader :value
def initialize(value)
@value = value
end
def bind
yield @value
end
def empty?
false
end
def inspect
"Just(#{@value.inspect})"
end
end
class Nothing < Maybe
include Singleton
def bind
self
end
def empty?
true
end
def inspect
"Nothing"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment