Registered: Mar, 2006
Re: Lexical Scope of Java Inner Classes and Closures
Posted: Jun 14, 2007 2:46 PM
Yes, of course you can translate callcc examples to Java: Java's turing complete. The point is that it requires global code restructuring.
As an exercise, try to implement amb using your callcc. Amb is the angelic operator, and can be easily implemented using continuations. It works like this:
a = choose(1, 2, 3, 4, 5, 6)
b = choose(1, 2, 3, 4, 5, 6)
assert(a + b == 7) # try other numbers if a + b != 7
print a, b # will only print a's and b's that sum to 7
assert(false) # next possibility
Amb arranges the variables so that tests do not fail. This code will print all numbers from 1 to 6 that sum to 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1. Yes this is magic.
Yes you can do this with a simple loop, but it will get real hairy for more complex examples, especially if amb is used as the return value of a function:
a = choose(*(0..x))
b = choose(*(0..x))
assert(a + b == 7)
a, b = foo(6)
print a, b
assert(false) # next one
You need to inline foo (global restructuring) if you want to change this to a loop.
def only_pythagorean_triples(a, b, c)
assert(a**2 + b**2 == c**2)
return [choose(*(0..x)), choose(*(0..x)), choose(*(0..x))]
a, b, c = three_numbers_upto(100)
only_primes(a) # try again if a isn't prime
only_pythagorean_triples(a, b, c) # try again if a, b, c is not a pythagorean triple
print a, b, c # here we have a pythagorean triple a, b, c, and a is prime.
Can you see the very high level abstraction? This abstraction is lost if you have to inline all functions and put them in a loop.
Here's a Ruby amb: http://www.rubyquiz.com/quiz70.html