by LeoPanthera · 2y ago · 0 comments
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) 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? (loop for i below 10 when (zerop (mod i 3)) collect (* i i)) (iter (for i below 10) (if (zerop (mod i 3)) (collect (* i i)))) 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.
let xs = [x*x | x <- [0..], x `mod` 3 == 0]
You can decide later how many you actually want.
(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…