Clojure Goodness: Flatten Collections
We can use the flatten
function when we have a collection with nested sequential collections as elements and create a new sequence with the elements from all nested collections.
In the following example we use the flatten
function:
(ns mrhaki.sample
(:require [clojure.test :refer [is]]))
;; Elements from nested sequential collections are flattend into new sequence.
(is (= [1 2 3 4 5] (flatten [1 [2 3] [[4]] 5])))
(is (sequential? (flatten [1 [2 3] [[4]] 5])))
(is (= [1 2 3 4 5] (flatten [[1] [2 3] [[4 5]]])))
;; We can use different sequential collection types.
;; We might have to force a type to a sequential collection with seq.
(is (= '(1 2 3 4 5) (flatten [1 (seq (java.util.List/of 2 3)) ['(4 5)]])))
(is (= (quote (1 2 3 4 5)) (flatten [[1] [(range 2 6)]])))
;; flatten on nil returns empty sequence.
(is (= () (flatten nil)))
Written with Clojure 1.10.1.