Skip to content

Instantly share code, notes, and snippets.

@thoferon
Last active December 11, 2015 13:09
Show Gist options
  • Save thoferon/4605780 to your computer and use it in GitHub Desktop.
Save thoferon/4605780 to your computer and use it in GitHub Desktop.
Simple example to understand monads for Rubyists. See http://en.wikipedia.org/wiki/Monad_(functional_programming)#Formal_definition.
class Monad
attr_reader :value
def bind(f)
raise "not implemented"
end
def self.return(v)
self.new v
end
def initialize(value)
@value = value
end
def self.construct(monad, *methods)
if methods.empty?
monad
else
construct(monad.bind(methods.first),
*methods[1..-1])
end
end
end
class ReachedLimit < Monad
def self.bind(f)
ReachedLimit
end
end
class Result < Monad
def bind(f)
result = f.call self.value
result > 1000 ? ReachedLimit : Result.new(result)
end
end
def twice(a)
2 * a
end
def plus100(a)
100 + a
end
def times4(a)
4 * a
end
def times200(a)
200 * a
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment