On Fri, Sep 11, 2015 at 2:31 AM, wrote:
On Thu, Sep 10, 2015, at 11:59, Steven D'Aprano wrote:
Although, I'm not sure that I agree with the idea that "everything is an
expression". I think that's a category mistake, like asking for the speed
of dark[1], or for a bucket of cold. Some things are functional by
and other things are imperative; some may be both, but I don't think that
assignment is one. I think that assignment is imperative, not functional,
and forcing it to return a value is artificial.
Why shouldn't imperative things be expressions? Why should all
expressions return a value?

I'm not sure what the point would be of having an expression that
doesn't return a value. The point of assignment-as-an-expression is
that you can do other things with the result:

while ((ch=getchar()) != EOF)

In Python, we have a couple of cases where that's done with the 'as' keyword:

with open(fn) as in_file:

except KeyError as e:

and there've been proposals now and then to have the same thing added
to if and while, which actually isn't hard:

while getchar() as ch:

but the trouble is that you can check for falsiness, but nothing else.
(In C, EOF is an integer outside the range 0..255, such that it's
distinct from any byte value. It's usually -1.) If assignment is an
expression, you can capture a value and keep going - something like

stash = [None]
while (stash.__setitem__(0, getchar()) or stash[0]) != -1:
     ch = stash[0]

It's ugly, but it does work - because the setitem call is an
expression. However, for this to succeed, the expression MUST yield a
value. Otherwise it doesn't make sense, and the difference between
expression and statement is a purely technical/theoretical one. (In
this case, the value of the "assignment" expression is always None,
which is less useful than C's policy of returning the value itself;
but at least I know what it's going to be, so I can use the "or
stash[0]" notation.)

Having assignment be a statement (and therefore illegal in a loop
condition) makes sense. Having it be an expression that yields a
useful or predictable value makes sense. Having it be an expression,
but not returning a value, doesn't.

(I'm not going to get into the argument here about whether assignment
SHOULD be a statement or an expression. There are plenty of languages
to choose from, so you can have it both ways if you like.)


Search Discussions

Discussion Posts


Follow ups

Related Discussions



site design / logo © 2018 Grokbase