Last active
March 22, 2017 13:07
-
-
Save zobar/6779692 to your computer and use it in GitHub Desktop.
Writer monad 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
class Writer | |
def flat_map | |
self.class.new do | |
value, log = get | |
new_value, new_log = yield value | |
[new_value, log + new_log] | |
end | |
end | |
def map | |
flat_map do |value, log| | |
new_value, log_item = yield value, log | |
[new_value, [log_item]] | |
end | |
end | |
def get | |
@result ||= @block.call | |
end | |
def initialize(&block) | |
@block = block | |
end | |
end | |
def Writer(value) | |
Writer.new { [value, []] } | |
end | |
w = Writer(5) | |
w1 = w.map { |v| [v * 2, 'multiplied by 2'] } | |
w2 = w1.flat_map { |v| [v + 1, ['added 1', 'with finesse']] } | |
w3 = w1.map { |v| ["Result is #{v}", 'stringified'] } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment