Skip to content

Instantly share code, notes, and snippets.

@okuramasafumi
Created March 19, 2022 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okuramasafumi/368facac392721582b5105a71c6b8168 to your computer and use it in GitHub Desktop.
Save okuramasafumi/368facac392721582b5105a71c6b8168 to your computer and use it in GitHub Desktop.
Algebraic Effects with Ruby
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