Can the if be implemented using call / cc?

I was told that “call / cc” can be used to implement arbitrary control flow constructs, so I am trying to implement all such constructions using “call / cc”, but I am having problems. Assuming I didn't have an if, how would I implement it with define-syntax and call / cc? Is it possible, or was I misled? I know how to implement an unconditional jump using "call / cc", but at the machine level, conditional execution is executed with branch instructions, the execution of which depends on the processor status bit. Without constructs of this type, I cannot see how this can be done.

+4
source share
2 answers

You cannot - you must have a way to test things and act, whether they are true or false. You can get closer, albeit with some functional representation of the logic elements. For example, with a common church encoding:

(define (true xy) x) (define (false xy) y) 

and now you can consider the test (which returns one of these encoded logic gates) as a function that accepts a “successful” continuation and a “failure”, and uses this to continue:

 (define (if cxy) (cxy)) 

If you want to experiment with this, you need to consider the fact that Scheme is not a lazy language, so you need to do something. For instance:

 (define (true xy) (x)) (define (false xy) (y)) (define-syntax if [(if cxy) (c (lambda () x) (lambda () y))]) 

(But you still need to reconsider existing predicates, etc., to return these Booleans.)

In any case, call/cc alone doesn't do anything suitable ...

+7
source

You can implement , if , only procedures of a higher order. This is an obvious unfounded church encoding:

 IF ? TE === (? (lambda () T) (lambda () F)) TRUE === (lambda (t _) (t)) FALSE === (lambda (_ f) (f)) 

You do not need to continue. True is a binary function that executes the first argument; False is a binary function that executes the second argument. If it is a triple function that combines them sequentially, getting the True / False value determined by the test (?), And giving it two functions that delay subsequent events.

+2
source

All Articles