4 ms·
I love Python's list comprehensions. When I first discovered them I had a kind of "mind blown" moment. They look like this, for anyone who doesn't know: squa
by LeoPanthera 3y ago
I love Python's list comprehensions. When I first discovered them I had a kind of "mind blown" moment. They look like this, for anyone who doesn't know:
squared_div_by_3 = [i**2 for i in range(10) if i % 3 == 0]
Without using a list comprehension, this is equivalent to:
squared_div_by_3 = []
for i in range(10):
if i % 3 == 0:
squared_div_by_3.append(i**2)
- pierrebai 3y agoOf course, Python would have been way more awesome if they did not reject the much more reader-friendly and idiomatic: squared_div_by_3 = [ for i in range(10): if i % 3 == 0: i**2 ] That is, just transforming the normal for loop and if into a list comprehension by surrounding it with brackets. It would even preserve the friendly forced blocking and indentation. Can you imagine?
- thaumasiotes 3y agoThere seems to have been a design emphasis in C# on providing something similar under the name LINQ. It would look like this: var squared_div_by_3 = from i in Enumerable.Range(0,10) where i % 3 == 0 select i*i; or alternatively: var squared_div_by_3 = Enumerable.Range(0,10).Where(i => i % 3 == 0).Select(i => i*i); In that second syntax, `Where` is exactly equivalent to Python's `filter` (or lisp's `remove-if-not`) and `Select` is of course equivalent to `map`; I assume the odd choice of names for C# is meant to appear similar to SQL. They're introducing Range objects with syntactic sugar so you can say `0..10` instead of `Enumerable.Range(0,10)`, and you'd think there would be LINQ implementations for those objects, but there aren't.
- ClimaxGravely 3y agoI've not used python much but is that not the same/similar to the unfold function in functional languages?
- LispSporks22 3y agoReads less like Perl in Lisp: (loop for i below 10 when (zerop (mod i 3)) collect (* i i))
- darthrupert 3y agoAre you joking?
- a-french-anon 3y agoWith iterate, for comparison: (iter (for i below 10) (if (zerop (mod i 3)) (collect (* i i))))
- srcreigh 3y agoIn racket: (for/list ([i (in-range 10) #:when (zero? (remainder i 3))]) (pow i 2)) there’s also for/vector for/and for/or for/first for/last, most likely for/set. Hashes. can add your own, etc…
- yazzku 3y agoIn Haskell: let xs = [x*x | x <- [0..], x `mod` 3 == 0] You can decide later how many you actually want.