Skip to content

Instantly share code, notes, and snippets.

@daveworth
Created February 5, 2014 20:59
Show Gist options
  • Save daveworth/8832956 to your computer and use it in GitHub Desktop.
Save daveworth/8832956 to your computer and use it in GitHub Desktop.
fun with continuations and a puzzler
def square_with_continuation(x, continuation = ->(x) { x })
continuation.call(x*x)
end
1.9.3-p448 :004 > square_with_continuation(2)
=> 4
1.9.3-p448 :005 > square_with_continuation(2, ->(x){ x.to_s })
=> "4"
1.9.3-p448 :006 > square_with_continuation(2, :to_s.to_proc)
=> "4"
1.9.3-p448 :007 > square_with_continuation(2, &:to_s)
=> 4
def apply_with_optional_continuation(function, continuation = ->(x) { x })
Proc.new{ |p| continuation.call(function.call(p)) }
end
1.9.3-p448 :004 > squarer = apply_with_optional_continuation(->(x) { x*x })
=> #<Proc:0x007fc1ba921340@(irb):2>
1.9.3-p448 :005 > squarer.call(2)
=> 4
1.9.3-p448 :006 > squarer_plus = apply_with_optional_continuation(->(x) { x*x }, :to_s.to_proc)
=> #<Proc:0x007fc1ba8ab6b8@(irb):2>
1.9.3-p448 :007 > squarer_plus.call(2)
=> "4"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment