Skip to content

Instantly share code, notes, and snippets.

@long-long-float
Created January 8, 2014 14:13
Show Gist options
  • Save long-long-float/8317283 to your computer and use it in GitHub Desktop.
Save long-long-float/8317283 to your computer and use it in GitHub Desktop.
Maybe monad in ruby
class Maybe
def value
end
end
class Just < Maybe
attr_reader :value
def initialize(value)
@value = value
end
def method_missing(name, *args)
ret = @value.send(name, *args)
ret != nil ? just(ret) : nothing
end
def ==(other)
other.class != Nothing && @value == other.value
end
def to_s
"Just #{@value}"
end
end
class Nothing < Maybe
def value
nil
end
def method_missing(name, *args)
nothing
end
def ==(_)
false
end
def to_s
'Nothing'
end
end
def just(value)
Just.new value
end
def nothing
Nothing.new
end
#monad laws
#1
just('hello').upcase == just('hello'.upcase)
#2
just(just(10).value) == just(10)
#3
just('Hello').upcase.downcase == just('hello'.upcase).downcase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment