3 ms·
What you get is multiple bound variables. Using only map and filter it would be harder to do i.e.: [(x*y) for x in range(0,5) for y in range(0,x)]
by a-saleh 7y ago
What you get is multiple bound variables. Using only map and filter it would be harder to do i.e.:
[(x*y) for x in range(0,5) for y in range(0,x)]
- tom_mellior 7y agoTo get multiple variables you "just" have to nest lambdas. In Haskell, for instance: Prelude> concatMap (\x -> concatMap (\y -> [x * y]) [0..x]) [0..5] [0,0,1,0,2,4,0,3,6,9,0,4,8,12,16,0,5,10,15,20,25] Prelude> [x * y | x <- [0..5], y <- [0..x]] [0,0,1,0,2,4,0,3,6,9,0,4,8,12,16,0,5,10,15,20,25] I'd take the latter over the former any day. And yes, I did get an obscure type error on my first attempt at the concatMap version because I forgot to bracket x * y.
- omaranto 7y agoI'd replace the inner concatMap (\y -> [x+y]) with a simple map (\y -> x+y), or, if I'm honest, with map (x+). Here's hoping HN doesn't mess up the asterisks... EDIT: I've replaced all asterisks with plus signs, because I couldn't figure out how to protect them from HN.
- tom_mellior 7y agoYeah, I realized that later. It's still more obscure than the version with the list comprehension. In particular, the place where x is introduced is at the very beginning, but the values it can be bound to are at the end of the expression, and that is much less clear than "x <- [0..5]". The rule for asterisks is that they must be followed by whitespace to show up as asterisks, so you just need to format your code nicely :-) x * y works.