Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> E.g. Python's list comprehensions are merely syntactic sugar for filter + map, but they make functional code so much more readable.

Can't say I agree. Maybe it's because I worked with simple functional programming primitives like filter and map before I ever really worked with Python, but I find Python list comprehensions weirder and harder to read than things like Clojure's thread macros, Ruby blocks, or even just chaining functional method calls together using the normal dot syntax in Java or Scala.

They do look better than the equivalents shown in the official Python documentation¹:

  squares = list(map(lambda x: x**2, range(10)))
but that is exceptionally hideous and not what I'd consider a normal way to write functional code for dealing with collections or streams.

Seems like a Python workaround for a Python problem to me. ¯ \ _ ( ツ ) _ / ¯

--

1: https://docs.python.org/3/tutorial/datastructures.html



Yeah I think having some a few more methods on some types would be nicer than having global functions like `map`

for example, imagine if your example could be written as:

range(10).map(lambda x: x*2).list()

but as a list comprehension it's slightly shorter, but autocomplete isn't as good:

[x*2 for x in range(10)]

Also some historical context, Python's list comprehension are based on Haskell's


For whatever reason, having just the global functions feels more natural to me in Lisps, but weirder where function names precede the opening parentheses.

I do also find the comprehensions more readable when one is actually using all of their components, i.e., when the function in the map behind the sugar would not be the identity function. But occasionally, when all the author really wanted to do is filter, you'll see stuff like

  [x for x in ... if ...]
and that always strikes me as a bit weird and unfortunate.

> Also some historical context, Python's list comprehension are based on Haskell's

I didn't know that! I do kinda like Python's preference for English keywords over arrows here, even though the Haskell syntax is more concise or whatever.


I guess preferences vary but to me [x**2 for x in range(10)] is a lot easier to read at a glance than range(10).map(x -> x**2).


Haskell always seemed like it was meant for the really mathematical subset of compsci that loves notation and that's why some of those who really love compsci love it.


Incidentally, Haskell has list comprehensions so you could write

  [x^2 | x <- [1..10]]
which looks about as legible as the Python version.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: