List Comprehensions

Rustom Mody rustompmody at gmail.com
Mon Dec 22 12:45:55 EST 2014


On Monday, December 22, 2014 8:37:50 PM UTC+5:30, Chris Angelico wrote:
> On Tue, Dec 23, 2014 at 1:58 AM, Rustom Mody wrote:
> > If you consider side-effecting comprehensions as kosher,
> > then a next conclusion is naturally going to be that
> > multiple generator comprehensions are confusing and therefore
> > not kosher -- a very unfortunate conclusion IMHO.
> 
> Why does that follow? What has that to do with side effects?

A comprehension means two things

1. There is the standard de-sugaring in terms of for-loops given in the docs 
that Steven repeated above.

2.There is this picture (needs to be seen in fix-pitch font)

[f(x) for x in [x₁  x₂  x₃  …  xₙ]]

means

[x₁  x₂  x₃  …  xₙ]
 ↓   ↓   ↓      ↓
[fx₁ fx₂ x₃  …  fxₙ]

There are not just two different ways of writing that for-loop -- upwards and downwards -- there are n! ways.

And even that assumes that each arrow is atomically and sequentially performed.

An assumption quite ok for a sequential machine completely unnecessary for a programmer.  Give up that assumption and the ways are infinite

IOW the second view is more abstract and programmer friendly than the first
in the same way that
saying the C expression "x+1"
"Adds 1 to the variable x"

rather than saying

"Its the C version of add 1, %eax"
[Why not inc %eax ?]

And this despite the fact that mathematical integers and real are rather far
removed from C's int and float.  IOW white lies are preferable to exact precise 
gobbledygook.

If the semantics of the comprehension depends on the order of the arrows,
the comprehension is screwed


Shorter technological answer:
In Haskell a side-effecting function gets a monadic type -- the type carries the
moniker "I am side-effecting" and so it cant be put in to a comprehension without type errors.

Now python's type system cannot do what Haskell's can [for better or worse is 
another matter -- a strong type system can be neat or a pain]

Considering that python's comprehensions are cloned from Haskell, it seems fair
that Haskell's formal strictures be passed on to beginners at least informally



More information about the Python-list mailing list