Skip to content

Instantly share code, notes, and snippets.

@zobar
Last active March 22, 2017 13:07
Show Gist options
  • Save zobar/6779692 to your computer and use it in GitHub Desktop.
Save zobar/6779692 to your computer and use it in GitHub Desktop.
Writer monad in ruby
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