Created
February 5, 2014 20:59
-
-
Save daveworth/8832956 to your computer and use it in GitHub Desktop.
fun with continuations and a puzzler
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
def square_with_continuation(x, continuation = ->(x) { x }) | |
continuation.call(x*x) | |
end |
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
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 |
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
def apply_with_optional_continuation(function, continuation = ->(x) { x }) | |
Proc.new{ |p| continuation.call(function.call(p)) } | |
end |
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
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