Clojure: Semi-Flattening a nested Sequence

后端 未结 5 722
走了就别回头了
走了就别回头了 2020-12-04 18:59

I have a list with embedded lists of vectors, which looks like:

(([1 2]) ([3 4] [5 6]) ([7 8]))

Which I know is not ideal to work with. I\'d lik

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 20:01

    To turn a list-of-lists into a single list containing the elements of every sub-list, you want apply concat as nickik suggests.

    However, there's usually a better solution: don't produce the list-of-lists to begin with! For example, let's imagine you have a function called get-names-for which takes a symbol and returns a list of all the cool things you could call that symbol:

    (get-names-for '+) => (plus add cross junction)
    

    If you want to get all the names for some list of symbols, you might try

    (map get-names-for '[+ /]) 
    => ((plus add cross junction) (slash divide stroke))
    

    But this leads to the problem you were having. You could glue them together with an apply concat, but better would be to use mapcat instead of map to begin with:

    (mapcat get-names-for '[+ /]) 
    => (plus add cross junction slash divide stroke)
    

提交回复
热议问题