Last active
December 11, 2015 13:09
-
-
Save romulodl/4605767 to your computer and use it in GitHub Desktop.
Just pasting here / code by https://github.com/thoferon
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
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 | |
# irb(main):009:0> Monad.construct(Result.return(1.1), method(:twice), method(:times200), method(:plus100), method(:twice)) | |
# => ReachedLimit | |
# irb(main):010:0> Monad.construct(Result.return(1.1), method(:twice), method(:plus100), method(:twice)) | |
# => #<Result:0x1065003f0 @value=204.4> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment