Stan Kurilin
Stan Kurilin

Reputation: 15792

When I should make sequence from lazy sequence

I'm reading Programming Clojure now and I find out next example

(defn by-pairs [coll]
  (let
    [take-pair (fn [c] (when (next c) (take 2 c)))]
    (lazy-seq
      (when-let [pair (seq (take-pair coll))] ;seq calls here
        (cons pair (by-pairs (rest coll)))))))

it breaks list into pairs, like

(println (by-pairs  [1 2 1]))     ((1 2) (2 1))
(println (by-pairs  [1 2 1 3]))   ((1 2) (2 1) (1 3))
(println (by-pairs  []))          ()
(println (by-pairs  [1]))         ()

What I can not get is why we should invoke seq on take-pair result? So why we can not just write

(defn by-pairs [coll]
  (let
    [take-pair (fn [c] (when (next c) (take 2 c)))]
    (lazy-seq
      (when-let [pair (take-pair coll)]
        (cons pair (by-pairs (rest coll)))))))

In witch cases there are will be different results or are there are any performance reasons?

Upvotes: 2

Views: 99

Answers (1)

Ankur
Ankur

Reputation: 33637

Both the code are same and there will be no difference because next and take functions that are being applied to coll in take-pair function, do call seq on the passed parameter i.e next c will first call seq on c or try to check if it is an object which implements ISeq and same in being doing by the take function. So basically in this case if you don't call seq yourself, the next and take will call seq on it.

Upvotes: 2

Related Questions