Splat inside an array comprehension

Hey all, embarrassed to say I’ve been a couple releases behind, but I’m starting to write more julia again and loving 0.5

Something I lost track of, however, is array comprehensions that are automatically flattened. Supposing I have an array of Dicts storing ngram info and I want an array all the ngrams from all the Dicts:

docs = [ Dict("pts," => 22, "forc" => 11), Dict("cass" => 72, "iora" => 44) ]

There used to be comprehensions that used [ ... ] and comprehensions that used { ... }, and we could write:

[ collect(keys(doc)) for doc in docs ]

But I’ve read enough to understand why that’s gone. Unfortunately the closest replacement I’ve found is:

collect(Base.Iterators.flatten([ collect(keys(doc)) for doc in docs ]))

Which isn’t horrible, but is definitely a mouthful.

I’m sure this has been discussed somewhere I’ve not found, but does something like this make sense:

[ collect(keys(doc))... for doc in docs ]

Or is there another way I’m missing entirely?

Thanks! Sorry for being so behind the times!

1 Like

I usually use a nested list comprehension for this sort of thing (in Julia and also in Python):

julia> [k for doc in docs for k in keys(doc)]
4-element Array{String,1}:
 "pts,"
 "forc"
 "cass"
 "iora"
2 Likes

Ah, that makes sense, thanks

I’ve wished this syntax was supported several times - it’s such a natural extension of splatting. It should be a straight-forward lowering transformation.

3 Likes