Clojure: Semi-Flattening a nested Sequence

后端 未结 5 727
走了就别回头了
走了就别回头了 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 19:42

    The code for flatten is fairly short:

    (defn flatten
      [x]
      (filter (complement sequential?)
        (rest (tree-seq sequential? seq x))))
    

    It uses tree-seq to walk through the data structure and return a sequence of the atoms. Since we want all the bottom-level sequences, we could modify it like this:

    (defn almost-flatten
      [x]
      (filter #(and (sequential? %) (not-any? sequential? %))
        (rest (tree-seq #(and (sequential? %) (some sequential? %)) seq x))))
    

    so we return all the sequences that don't contain sequences.

提交回复
热议问题