'if' as a _function_, in Scheme and Python

Neel Krishnaswami neelk at brick.cswv.com
Thu Aug 19 20:22:16 EDT 1999


On Thu, 19 Aug 1999 22:31:49 GMT, oleg at pobox.com <oleg at pobox.com> wrote:
>In most languages, 'if' has a distinguished status, of a statement or
>a special syntax form. One wonders whether 'if' can be a regular
>function. 
>
>For example, in Scheme:
>        (define (my-if condition then-branch else-branch)
>           ((or (and condition then-branch) else-branch)))
>
>on stipulation that the arguments of this function are wrapped in
>lambda-expressions (i.e., thunks):

You should look also look at Smalltalk; all operations are implemented
with message sends, and conditionals are implemented exactly as you
describe (ie with closures). Python is more like a Smalltalk than a
Scheme (to the extent that's meaningful -- ST and Scheme are
practically duals in language space). 

>x = eval((lambda: exp1, lambda: exp2)[not condition].func_code,vars())
>
>this expression is equivalent to
>        if condition: x = exp1
>        else: x = exp2

Wow. That's probably the best ?: emulation yet. "Best" being defined
as "makes me laugh with appreciation," as opposed to actually being
practical; the if-else construction is the only one that J. Random
Hacker is likely to understand when he comes across in actual code.


Neel




More information about the Python-list mailing list