'if' as a _function_, in Scheme and Python
barmar at bbnplanet.com
Thu Aug 19 20:24:25 EDT 1999
In article <37bc9dd6.11041486 at 126.96.36.199>,
Steve Schafer <pandeng at telepath.com> wrote:
>On Thu, 19 Aug 1999 22:31:49 GMT, oleg at pobox.com wrote:
>>To show it clearer, let me re-write my-if as
>> (define (my-if condition then-branch else-branch)
>> ((cdr (assq (eq? condition #f)
>> (list (cons #t else-branch) (cons #f then-branch))))))
>>This definition is _purely_ functional
>Not only is it purely functional, it also unconditionally evaluates
>both branches (in Scheme). Therefore, it is not equivalent to IF.
No. 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").
The subject of a functional "if" comes up in the Scheme group every 6-9
months, I think. The above implementation is clever. A more common
implementation involves replacing #t and #f with functions:
(define (if-true then-branch else-branch)
(define (if-false then-branch else-branch)
Predicates return if-true or if-false instead of #t or #f, respectively (we
could define that these special values actually evaluate to these
functions). Then "if" is defined as:
(define (if condition then-branch else-branch)
(condition then-branch else-branch))
Barry Margolin, barmar at bbnplanet.com
GTE Internetworking, Powered by BBN, Burlington, MA
*** DON'T SEND TECHNICAL QUESTIONS DIRECTLY TO ME, post them to newsgroups.
Please DON'T copy followups to me -- I'll assume it wasn't posted to the group.
More information about the Python-list