Skip to content

Instantly share code, notes, and snippets.

@softa
Created May 26, 2010 02:23
Show Gist options
  • Save softa/413971 to your computer and use it in GitHub Desktop.
Save softa/413971 to your computer and use it in GitHub Desktop.
##
# Identity Monad for Ruby taken from
# http://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/00introduction.html
# ... but without the typos and with complete functions
##
class Identity
attr_reader :value
def initialize( value )
@value = value
end
def self.wrap( value )
new(value)
end
def pass
yield @value
end
end
def f(v); Identity.wrap(5*v); end
def g(v); Identity.wrap(10*v);end
# 1st law
result = Identity::wrap( 5 ).pass do |value|
f(value)
end
puts result.value == f(5).value
# 2nd law
someidentity = Identity.new(5)
result = someidentity.pass do |value|
Identity::wrap( value )
end
puts result.value == Identity.new(5).value
# 3rd law
r1 = someidentity.pass do |value_a|
f( value_a )
end.pass do |value_b|
g( value_b )
end
r2 = someidentity.pass do |value_a|
f( value_a ).pass do |value_b|
g( value_b )
end
end
puts r1.value == r2.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment