Reputation:
I have this function which seems to work fine on limited collections, but not on infinite ones. Is there a way to construct a lazy-seq
in it to get it run with infinite coll's, like: (take 3 (m inc (range)))
=> (1 2 3)
?
(defn m [f c] (reduce #(conj % (f %2)) [] c))
Upvotes: 0
Views: 261
Reputation: 5598
reduce
will keep taking elements from a sequence until nil
gets returned. As such, reduce
will never return on infinite sequences.
As pointed out in the comments, reduced
can be used to force the termination of reduce
, thanks!
Upvotes: 1
Reputation: 426
This seems to be a use case for map
(map f c)
or (when it had to be a vector)
(mapv f c)
EDIT: A possible re-implementation of map:
(defn new-map [f coll]
(if (seq coll)
(lazy-seq
(cons (f (first coll))
(new-map f (rest coll))))))
Upvotes: 2