Skip to content

Instantly share code, notes, and snippets.

@pzol
Created March 28, 2012 13:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pzol/2225971 to your computer and use it in GitHub Desktop.
Save pzol/2225971 to your computer and use it in GitHub Desktop.
Maybe in ruby
def Maybe(obj)
return Maybe.new(Nothing.new) if obj.nil?
return Maybe.new(obj)
end
class Nothing
def method_missing(*args, &block)
self
end
def ==(other)
other.is_a? Nothing
end
end
class Maybe
def initialize(value)
@value = value
end
def nothing?
@value.is_a? Nothing
end
alias :empty? :nothing?
def value(default)
return default if nothing?
return @value
end
def else(default)
return default if nothing?
return self
end
def method_missing(m, *args)
Maybe(@value.__send__(m, *args))
end
def ==(other)
@value == other.instance_variable_get(:@value)
end
end
require 'minitest/autorun'
require_relative 'maybe'
class MaybeTest < MiniTest::Unit::TestCase
def test_nil
assert_equal Maybe(nil).a.b.c, Maybe(Nothing.new)
end
def test_some
assert_equal Maybe("Some").downcase, Maybe("some")
end
def test_value_with_nil
assert_equal Maybe(nil).a.value("foo"), "foo"
end
def test_value_with_some
assert_equal Maybe("Some").downcase.value("nothing"), "some"
end
def test_else_with_nil
assert_equal Maybe(nil).else("foo"), "foo"
end
def test_else_with_some
assert_equal Maybe("Foo").else("bar"), Maybe("Foo")
end
end
@pzol
Copy link
Author

pzol commented Apr 30, 2012

Please see https://github.com/pzol/monadic for a more complete implementation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment