Skip to content

Instantly share code, notes, and snippets.

@pzol
Created Mar 28, 2012
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@pzol 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