1.3.0 permalink Arrow_down_16x16

interleave

clojure.core

  • (interleave c1 c2)
  • (interleave c1 c2 & colls)
Returns a lazy seq of the first item in each coll, then the second etc.

5 Examples top

  • ;; This example takes a list of keys and a separate list of values and 
    ;; inserts them into a map.
    user=> (apply assoc {} 
             (interleave [:fruit :color :temp] 
                         ["grape" "red" "hot"]))
    
    {:temp "hot", :color "red", :fruit "grape"}
    
  • ;; Simple example:
    user=> (interleave [:a :b :c] [1 2 3])
    (:a 1 :b 2 :c 3)
  • ;; The shortest input stops interleave:
    
    user=> (interleave [:a :b] (iterate inc 1))
    (:a 1 :b 2)
  • (def s1 [[:000-00-0000 "TYPE 1" "JACKSON" "FRED"]
             [:000-00-0001 "TYPE 2" "SIMPSON" "HOMER"]
             [:000-00-0002 "TYPE 4" "SMITH" "SUSAN"]])
    
    (interleave (map #(nth % 0 nil) s1) (map #(nth % 1 nil) s1))
  • (def s1 [[:000-00-0000 "TYPE 1" "JACKSON" "FRED"]
             [:000-00-0001 "TYPE 2" "SIMPSON" "HOMER"]
             [:000-00-0002 "TYPE 4" "SMITH" "SUSAN"]])
    
    (def cols [0 2 3])
    
    (defn f1 
      [s1 col] 
      (map #(get-in s1 [% col] nil) (range (count s1))))
    
    (apply interleave (map (partial f1 s1) cols))
    (:000-00-0000 "JACKSON" "FRED" :000-00-0001 "SIMPSON" "HOMER" :000-00-0002 "SMITH" "SUSAN")
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:3820 top

(defn interleave
  "Returns a lazy seq of the first item in each coll, then the second etc."
  {:added "1.0"
   :static true}
  ([c1 c2]
     (lazy-seq
      (let [s1 (seq c1) s2 (seq c2)]
        (when (and s1 s2)
          (cons (first s1) (cons (first s2) 
                                 (interleave (rest s1) (rest s2))))))))
  ([c1 c2 & colls] 
     (lazy-seq 
      (let [ss (map seq (conj colls c2 c1))]
        (when (every? identity ss)
          (concat (map first ss) (apply interleave (map rest ss))))))))
Vars in clojure.core/interleave:
Used in 0 other vars

Comments top

No comments for interleave. Log in to add a comment.