Created
March 28, 2012 13:06
-
-
Save pzol/2225971 to your computer and use it in GitHub Desktop.
Maybe in ruby
This file contains hidden or 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
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 |
This file contains hidden or 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 '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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please see https://github.com/pzol/monadic for a more complete implementation