(test) ? a:b

Ian Kelly ian.g.kelly at gmail.com
Thu Oct 23 16:24:07 CEST 2014


On Thu, Oct 23, 2014 at 7:44 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> However, the "[f, g][cond]()" technique is how pure lambda calculus
> implements conditional branching so it is interesting in its own right.

I wasn't aware that lambda calculus had lists and indexing built in.

> IOW, you can do "short-circuiting" in purely functional programming:
>
>     j = j + 1 if j < 10 else 3
>
>     <=>
>
>     j = (lambda: 3, lambda: j + 1)[j < 10]()

The implementation given by Wikipedia (and translated into Python by me) is:

>>> true = lambda x: lambda y: x
>>> false = lambda x: lambda y: y
>>> ifthenelse = lambda p: lambda a: lambda b: p(a)(b)
>>> ifthenelse(true)(1)(2)
1
>>> ifthenelse(false)(1)(2)
2

For demonstration purposes I used Python ints as the branches rather
than actual lambda calculus constructs, but this shows how selection
can be done using only lambda abstractions and applications.

In any case I don't see how this relates to the "[f, g][cond]()"
technique of Python, unless you just meant the general approach of
first selecting a function and then applying it. In that sense though,
the ternary operator does the same thing; the application is just done
invisibly by the language in the form of evaluating an expression as
opposed to explicitly applying a function.



More information about the Python-list mailing list