Blair Davidson
Blair Davidson

Reputation: 941

Clojure where is left fold

Does clojure implement left fold or right fold?

I understand there is a new library reducers which has this but shouldn't it exists in clojure.core?

Upvotes: 0

Views: 634

Answers (2)

noisesmith
noisesmith

Reputation: 20194

As Thumbnail points out, reduce-right cannot be efficiently implemented on the jvm for sequences. But as it turns out, we do have a family of data types that can do efficient lookup and truncation from the right side. reduce-right can be implemented for vectors.

user> 
(defn reduce-right
  [f init vec]
  (loop [acc init v vec]
    (if (empty? v)
      acc
      (recur (f acc (peek v)) (pop v)))))

#'user/reduce-right
user> (count (str (reduce-right *' 1 (into [] (range 1 100000))))) ; digit count
456569

Upvotes: 0

Thumbnail
Thumbnail

Reputation: 13473

Clojure implements a left fold called reduce.

Why no right fold?

  • reduce and many other functions work on sequences, which are accessible from the left but not the right.

The new reducers and transducers are designed to work with associative functions on data structures of varying accessibility.

Upvotes: 4

Related Questions