Created
March 19, 2022 14:17
-
-
Save okuramasafumi/368facac392721582b5105a71c6b8168 to your computer and use it in GitHub Desktop.
Algebraic Effects with Ruby
This file contains 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 WithEffect | |
def initialize | |
@list = ["Foo", "Bar", 42, "Baz"] | |
end | |
def process_item(item) | |
throw(:item_not_string, 42) unless item.is_a?(String) | |
puts item | |
end | |
def signal_handler | |
lambda do |signal, b, alternative_proc| | |
b.local_variable_set(:item, alternative_proc.call(signal)) | |
true | |
end | |
end | |
def iterate(alternative_proc = ->(signal) { "ALTERNATIVE#{signal}" }) | |
@list.each do |item| | |
signal = catch(:item_not_string) do | |
process_item(item) | |
end | |
redo if signal && signal_handler.call(signal, binding, alternative_proc) | |
end | |
end | |
end | |
WithEffect.new.iterate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment