3 ms·
For me it’s very rare and used where I would write something like concatMap in Haskell. citiesByState = { 'WA': ['Seattle', 'Spokane', 'Olympia'],
by klodolph 8y ago
For me it’s very rare and used where I would write something like concatMap in Haskell.
citiesByState = {
'WA': ['Seattle', 'Spokane', 'Olympia'],
'OR': ['Portland', 'Salem'],
'CA': ['San Francisco', 'Los Angeles', 'San Diego'],
}
cityToState = {city: state
for state, cities in citiesByState.items()
for city in cities}
I would generally avoid multiple levels in a comprehension but there are some very simple two-level cases like this that I use occasionally. I feel that the code is easy to read, at least.
- evincarofautumn 8y agoIn Haskell, these direct equivalents aren’t bad at all: cityToState = Map.fromList [ (city, state) | (state, cities) <- Map.toList citiesByState , city <- cities ] cityToState = Map.fromList $ do (state, cities) <- Map.toList citiesByState city <- cities pure (city, state) For multiple “nested loops”, I generally prefer do-notation over both list comprehensions and combinators such as concatMap, unless the structure is simple enough that the combinator version is much shorter.
- klodolph 8y agoAnd for those following who don’t know Haskell, both of these are basically sugar for concatMap. (>>=) = flip concatMap