functional-programmingschemecontrol-flowcallccdefine-syntax

Can "if" be implemented using "call/cc"?


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.


Solution

  • 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...