Can "if" be implemented using "call/cc"?
Asked Answered
F

2

6

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.

Frosting answered 29/7, 2011 at 3:27 Comment(0)
L
8

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

Liber answered 29/7, 2011 at 3:40 Comment(2)
I didn't think that you could. Defining boolean values as functions changes the semantics of the language in such a way that boolean operators would have to be redefined because in Scheme any function is non-false when considered as a boolean value.Frosting
Yes, such a change would result in a different language... That's why I started with "you can't".Liber
F
3

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.

Faveolate answered 17/11, 2012 at 18:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.