Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 526
N4tur41Myst1c Avatar asked Jul 29 '11 03:07

N4tur41Myst1c


2 Answers

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

like image 180
Eli Barzilay Avatar answered Sep 24 '22 01:09

Eli Barzilay


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.

like image 39
ChrisD Avatar answered Sep 25 '22 01:09

ChrisD