Reputation: 458
I want to coalesce multiple sequences into one lazy sequence. The caveat is that it seems that all the mechanisms in core (map, interleave, etc) to accomplish this will not account for those sequences being multiple lengths. I have seen this similar post but it's not exactly what I was looking for. So basically, the goal is a function "super-fn" that has these characteristics:
=>(defn super-fn [& rest]
...)
=>(apply println (super-fn [1 2 3 ] [1 2 3 4 5]))
1 1 2 2 3 3 4 5
=>nil
It seems like it would be useful to be able to coalesce multiple streams of data like this without knowing their lengths. Is my "super-fn" in the core library and I have just missed it or am I missing some hard aspect of doing this?
Upvotes: 1
Views: 354
Reputation: 2759
I'm not aware of any such function in the standard library.
It's not hard to write, though:
(defn super-fn
[& seq-seq]
(when seq-seq
(lazy-seq
(concat (filter identity
(map first seq-seq))
(apply super-fn
(seq
(filter identity
(map next seq-seq))))))))
Upvotes: 1
Reputation: 51450
I agree with bsvingen, though you could use slightly more elegant implementation:
(defn super-fn
[& colls]
(lazy-seq
(when-let [ss (seq (keep seq colls))]
(concat (map first ss)
(apply super-fn (map rest ss))))))
It also correctly handles empty input sequences:
(super-fn [1 2] []) ; => (1 2)
Upvotes: 3