Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the one-level sequence flattening function in Clojure?

What's the one-level sequence flattening function in Clojure? I am using apply concat for now, but I wonder if there is a built-in function for that, either in standard library or clojure-contrib.

like image 384
missingfaktor Avatar asked May 23 '12 15:05

missingfaktor


2 Answers

My general first choice is apply concat. Also, don't overlook (for [subcoll coll, item subcoll] item) -- depending on the broader context, this may result in clearer code.

like image 192
Marko Topolnik Avatar answered Oct 18 '22 10:10

Marko Topolnik


There's no standard function. apply concat is a good solution in many cases. Or you can equivalently use mapcat seq.

The problem with apply concat is that it fails when there is anything other than a collection/sequential is at the first level:

(apply concat [1 [2 3] [4 [5]]]) => IllegalArgumentException Don't know how to create ISeq from: java.lang.Long... 

Hence you may want to do something like:

(defn flatten-one-level [coll]     (mapcat  #(if (sequential? %) % [%]) coll))  (flatten-one-level [1 [2 3] [4 [5]]]) => (1 2 3 4 [5]) 

As a more general point, the lack of a built-in function should not usually stop you from defining your own :-)

like image 34
mikera Avatar answered Oct 18 '22 10:10

mikera