conditional expressions
Alex Martelli
aleax at aleax.it
Thu Sep 26 13:22:11 EDT 2002
Pedro RODRIGUEZ wrote:
...
>>> But why use grotesque hacks in the first place? "a ? b : c" is a
...
> Ada has two short-circuits operators : "and then" and "or else" that
> do the trick :
> if A and then B then
> ...
> end if;
>
> Looks cleaner to me.
Ada's "and then" is like Python's "and"; Ada;s "or else" is like
Python's "or". Neither is like C's "a?b:c" (ternary operator),
though with some tricks boolean shortcircuiting operators can be
used to simulate ternary operators (a bit cumbersome in the
general case).
The reason
zz = a and b or c
is not the same thing as
zz = a ? b : c
is that, when a is true and b is false, the former returns c,
while the latter returns b.
The tricks deal with ways to work around this problem, by
ensuring that and's RHO can never be false, e.g.
zz = (a and [b] or [c])[0]
The other traditional emulation of ternary operator is by
indexing, e.g.:
zz = (b, c)[not a]
and here the defect is that this isn't short-circuiting --
both the b and c sub-expressions are evaluated anyway, no
matter what's the value of a (this is a problem when,
e.g., b is actually a function call such as "fb()").
Here, the workarounds can use and/or if it's OK to
evaluate _a_ multiple times:
zz = (a and b, not a and c)[not a]
or lambdas:
zz = (lambda:b, lambda:c)[not a]()
The deeper problem with all of these "solutions" is that
they're unholy kludges, of course.
Alex
More information about the Python-list
mailing list