by saadq · 10y ago · 0 comments
JavaScript:
let arr = [1, 2, 3]
let sumOfSquares = arr.map(n => n * n).reduce((a, b) => a + b) // 14
Python: arr = [1, 2, 3]
sum_of_squares = reduce(lambda a, b: a + b, map(lambda n: n * n, arr)) # 14 sum_of_squares = sum([x*x for x in arr])
Which I think is easier to read than either example post above.Of course you will point out that this is less powerful than full map and reduce.. but meh... pros and cons to both styles
sum_of_squares = sum(x*x for x in arr)
This makes use of https://www.python.org/dev/peps/pep-0289/It's more than just stylistic.
But hey, if you want to use map when you actually need to do a parallel map, cool. But seems very very uncommon. ~ 1 in 10,000 maps I write.
I feel like I come down hard on the side of lambdas, but I've never really spent enough time in a language with list comprehension, so there's a good chance I'm missing something.
I'm from a non-list-comprehension background too, but recently started working a lot in a large python codebase, and have found the dict/list comprehensions to be beautiful. I'm a huge fan. It's a shame lambda syntax is not the best and it's generally crippled, but comprehensions are a great 80/20 compromise for handling most cases very cleanly.
In theory I suppose the VM could have a map() implementation which opportunistically extracts the code from a lambda and inlines them when possible; but doubt CPython does that. OTOH, I'd be surprised if PyPy doesn't do something like that.
[1] http://python-history.blogspot.com/2010/06/from-list-compreh...
from operator import mul, add
arr = [1, 2, 3]
sum_of_squares = reduce(add, map(mul, arr, arr)) (defn sum-of-squares [a] (reduce + (map #(* % %) a)))
(sum-of-squares [1, 2, 3]) ; => 14