I've been told that "call/cc" can be used to implement arbitrary control flow constructs so I'm trying to implement all such constructs using "call/cc" but I'm having trouble. Assuming I didn't have "if" how would I implement it using "define-syntax" and "call/cc"? Is it possible or have I been misled? I know how to implement an unconditional jump using "call/cc" but at the machine level conditional execution is performed with branching instructions whose execution depends on the status bits of the processor. Without constructs of this type I don't see how it can be done.
You can't -- you have to have some way to test things and act on whether they're true or false. You could get close though, with some functional representation of booleans. For example, with a common church encoding:
(define (true x y) x)
(define (false x y) y)
and now you can consider a test (that returns one of these encoded booleans) as a function that accepts a "success" continuation and a "failure" one, and uses that to continue:
(define (if c x y) (c x y))
If you want to experiment with this, you need to consider the fact that Scheme is not a lazy language, so you need to thunk things up. For example:
(define (true x y) (x))
(define (false x y) (y))
(define-syntax if
[(if c x y) (c (lambda () x) (lambda () y))])
(But you still need to revise existing predicates etc to return these booleans.)
Either way, call/cc
in itself isn't really doing anything relevant...
You can implement if with only higher-order procedures. This is the obvious uncurried Church encoding:
IF ? T E === (? (lambda () T) (lambda () F))
TRUE === (lambda (t _) (t))
FALSE === (lambda (_ f) (f))
You don't need continuations at all. True is a binary function that executes it's first argument; False is a binary function that executes it's second argument. If is a ternary function that sequences them together by getting the True/False determined by the test (?), and giving it the two functions that delay the consequents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With