4 ms·
I find comprehensions to be especially useful in two situations: 1. Transforming a list using some non-standard function, often with some basic input checking:
by apu 18y ago
I find comprehensions to be especially useful in two situations:
1. Transforming a list using some non-standard function, often with some basic input checking:
[int(x)*2+1 for x in seq if x]
(Here, we're assuming x is a string which can possibly be empty or only blanks)
2. Transforming elements from multiple lists together:
['Iter %d took %0.2f secs' % (i, t) for i, t in zip(iters, times) if t > 1.5]
(Where we want output strings only if some iteration took a long time)
Although I'm not too fluent in lisp, I think the equivalent formulations might be longer (since you'd have to write lambda, map, filter and many parens), and perhaps harder to decipher.
- PieSquared 18y agoBeat this short Arc snippet using map with a list comprehension: (def vector-dot-product (vector-1 vector-2) (map [* _1 _2] vector-1 vector-2)) That's from Light Makes Right the raytracer, I think. Equivalent python: def vectorDotProduct(vector1, vector2): return [x * y for x, y in zip(vector1, vector2)] I'm pretty sure that the Lisp snippet above is neither harder to decipher nor longer. Though maybe that's just because Arc is nice.
- apu 18y agoAgreed. This example highlights the great savings of the [... _ ...] syntax in Arc (which I'd imagine is a fairly common use-case, especially for map, filter, etc.). Although ironically in this case, I'd probably use the following: def vectorDotProduct(vector1, vector2): return map(op.mul, vector1, vector2) (where op has been imported previously using: import operator as op ) I'm not really sure how idiomatic this is, but I find that 90% of the time when I use map in python, it's with the operator module.
- lsb 18y agoin Haskell (and maybe ML), you might have vectorDotProduct = map (*)
- lincolnq 18y agoYou probably meant: vectorDotProduct = zipWith ( * ) (and this doesn't even include the sum) map ( * ) has type Num a => [a] -> [a -> a] which is not really what the dot product should be.