A library approach to the ternary operator

David Abrahams dave at boost-consulting.com
Sun Mar 23 08:33:08 EST 2003


Alex Martelli <aleax at aleax.it> writes:

> David Abrahams wrote:
>    ...
>
>>> somewhat important to pick a better name for the function...!).
>>> Another likely name might be "pick".
>> 
>>         y = choose(x < 0 and [22.5] or [f(x)])
>>         y = ternary(x < 0 and [22.5] or [f(x)])
>>         y = pick(x < 0 and [22.5] or [f(x)])
>>         y = cond(x < 0 and [22.5] or [f(x)])
>>         y = if_(x < 0 and [22.5] or [f(x)])
>> 
>> I guess I like the last two, and the last one best of all, because
>> in my mind there's a nice association between the function name and
>> the adjacent condition.
>
> My preferences differ -- using an ordinary, well-pronounceable
> English word such as 'choose' or 'pick' seems to make for clearer
> and more readable code than arbitrary abbreviations such as
> 'cond' for 'conditional' (no doubt familiar to LISPers, but, since
> the function's workings are SO different from Lisp's COND, I do
> not think the familiarity is necessarily an advantage) or things
> such as 'if_', hard to pronounce distinctly from keyword 'if'.

At one time I might've agreed with you, but I guess my viewpoint has
been changed by lots of experience with metaprogramming and the Boost
MPL (see http://www.mywikinet.com/mpl/ for some examples of how if_
works out).  In that domain there are so many names that are direct
analogies for keywords that code is way more-readable if we don't
shrink from them. So we have if_, while_, bool_, int_, for_, ...

I also note that while this thing is in fact a function, it will have
"keywordish" mental status from the standpoint of anyone reading the
code because of the distinctive pattern of its usage.

I appreciate your argument about COND, though, which is one reason I
didn't love it either.

I'm really looking for a name which the adjacent condition will tend
to associate with more closely than with the 'and' keyword.  Maybe
choose_if works, but it's uncomfortably long IMO.

Hmm,

         y = when(x < 0 and [22.5] or [f(x)])

Except for the temporal overtones I like that one.  I guess there's
also:

         y = where(x < 0 and [22.5] or [f(x)])

but I think I prefer "when".

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com




More information about the Python-list mailing list