PEP308 - Probably silly, but just a thought

Stephen Horne intentionally at blank.co.uk
Thu Feb 13 12:05:13 EST 2003


I've been reading about PEP308 (though not everything, obviously) and
had a thought about the ternary-operator like syntax proposal...

  condition then true-value else false-value

In itself, this notation is nothing special - friendlier that the
existing use of 'and' and 'or', but only a minor gain really and
certainly no better than the slightly-reminiscent-of-LISP version.

  (if condition : true-value else: false-value)

Yes, I'm a C and C++ programmer by default - that doesn't mean I have
to like the C ternary operator, even with more sensible operator
names.

However, what if it wasn't a ternary operator but instead two separate
binary operators. The operator meanings would be...

  a then b
    evaluate a - if true return b, if false trigger backtracking.

  a else b
    evaluate a - if successful return result, else return b.

This would be a lot like certain Icon expressions (but without the
annoying relative-operators-that-don't-return-truth-values).

The 'then' operator would basically be a quick assertion-style
validation operator, useful even without an else. And the else could
be used to catch exceptions from inside functions and provide
defaults, useful even without the 'then'.

Examples...

1.  else for providing a default

  print (x / y) else "Error"

2.  then as an assert

  def Checked_FN (x) :
    return (0 <= x < 10) then FN (x)

3.  In concert - note that -ve x causes fail condition, not infinite
recursion...

  def Factorial (x) :
    return ((x == 0) then 1) else ((x > 0) then x * Factorial (x - 1))

It might be possible to treat the backtracking from 'then' as an
exception with a standard name - though this is extremely suspect, I
admit. In reality, I imagine it would complicate the expression
compilation too much (or alternatively add an unnecessary overhead to
all expressions). There may also be a parsing issue with allowing the
'else' to be used as a separate operator without a prior 'then', but I
thought I'd mention it just in case.

-- 
steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list