0
votes

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?

2

2 Answers

4
votes

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.

0
votes

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