Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is clojure thread last (->>) a macro?

Tags:

macros

clojure

The only benefit I can see is that it means that one avoids calls to partial.

(defn foldl [f acc xs]
  (loop [acc acc
         xs xs]
    (if (empty? xs)
      acc
      (recur (f (first xs) acc) (rest xs)))))

(defn $ [f x] (f x))

(defn thread-last [x & rest]
  (foldl $ x rest))

which gives:

(thread-last (range 10)
             (partial map inc)
             (partial filter odd?)
             (partial reduce +)) => 25

(->> (range 10)
     (map inc)
     (filter odd?)
     (reduce +)) => 25

Are there any cases when a functional / explicit version would fail?

like image 592
beoliver Avatar asked Dec 25 '16 21:12

beoliver


1 Answers

First, note that your foldl is just reduce. Our language isn't that much poorer than Haskell!

Second, not all forms are function calls, and ->> can rewrite all forms. For example, you could use ->> to implement something a bit like Haskell's where clauses:

(defn mapcat' [f xs]
  (->> (apply concat mapped)
       (let [mapped (map f xs)])))

Not really a style that is popular with Clojure programmers, but it serves as an example of something ->> can do that partial can't.

like image 90
amalloy Avatar answered Nov 09 '22 23:11

amalloy