'if' as a _function_, in Scheme and Python

Patrick Logan patrick at c837917-a.potlnd1.or.home.com
Fri Aug 20 03:40:56 CEST 1999


In comp.lang.functional Barry Margolin <barmar at bbnplanet.com> wrote:

: Remember that then-branch and else-branch are thunks.  It doesn't
: matter whether you evaluate them, they don't do anything until you
: *call* them.  The above expression selects one of them and then
: calls it (notice the extra level of parentheses before "cdr").

: A more common implementation involves replacing #t and #f with
: functions:

: (define (if-true then-branch else-branch)
:   (then-branch))
: (define (if-false then-branch else-branch)
:   (else-branch))

BTW this is exactly the way "if" is implemented in Smalltalk.

  Boolean>>ifTrue: trueThunk ifFalse: falseThunk

...is a method that is redefined in Boolean's two subclasses, True and
False. For the class True, it is defined as...

  True>>ifTrue: trueThunk ifFalse: falseThunk

    "Return the result of the value of trueThunk"

    ^trueThunk value

and for class False...

  False>> ifTrue: trueThunk ifFalse: falseThunk

    "Return the result of the value of falseThunk"

    ^falseThunk value

Sending this message looks like...

    (a < b) ifTrue: [#yeah] ifFalse: [#boo]

...where (a < b) evaluates to either the singleton instance of True,
called true, or the singleton instance of False, called false.

The notation [<expression>] is a thunk like (lambda () <expression>)
in Scheme. With arguments a "lambda" in Smalltalk looks like...

    "This is a lambda that returns the sum of its arguments"
    [ :x :y | x + y]

-- 
Patrick Logan    patrickdlogan at home.com




More information about the Python-list mailing list