-
-
Save sescobb27/dd725e33b288111df987 to your computer and use it in GitHub Desktop.
Maybe Monad
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
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