[Python-ideas] FW: Map-then-filter in comprehensions
Joseph Jevnik
joejev at gmail.com
Tue Mar 8 13:57:12 EST 2016
Haskell has a feature like this in comprehensions where one may write: [r +
1| n <- [1..10], let r = n * 3, r `rem` 4 == 0]
Here we are sharing the definition of `r` in both the predicate and the
value expresions, we can also use the name in different expressions in both
contexts.
If we were to translate this to python syntax we could have something like:
[r + 1 for n in range(1, 11) for n * 3 as r if r % 4 == 0]
There is no reason that the name binding needs to be a part of the
predicate expression, they can just be seperate clauses. I think the `for
expr as name` is nice because it matches the order that comprehensions over
multiple iterators are evaluated like: `[n for n in ns for m in ms]`.
I personally just write `map` and `filter` and then have the control to
make the correct function get called first but adding something like this
might make me more inclined to use comprehensions for the simple cases.
On Tue, Mar 8, 2016 at 1:34 PM, Chris Angelico <rosuav at gmail.com> wrote:
> On Wed, Mar 9, 2016 at 5:32 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> > On 03/08/2016 10:27 AM, Chris Angelico wrote:
> >
> >> Implement that, and people will ask why they can't then unroll that:
> >>
> >> def <listcomp>():
> >> result = []
> >> for x, y in some_iterable:
> >> if x+y as z > 10: # SyntaxError
> >> result.append(z)
> >> return z
> >
> >
> > Seriously?
> >
> > def blah():
> > result = []
> > for x, y in some_iterable:
> > z = x + y
> > if z > 10:
> > result.append(z)
> > return result # not z
> >
> > That doesn't seem too difficult. ;)
>
> Ah yes, but that's not how you've written it in the comprehension. You
> wrote it with 'as'. Believe you me, people WILL expect that outside of
> comprehensions. Otherwise, you have to explain why a name binding is
> legal in a condition in a comprehension, but not in any other
> expression.
>
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160308/e46b5ab5/attachment.html>
More information about the Python-ideas
mailing list