Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: "thread-first" macro -> and "thread-last" macro ->>

Tags:

clojure

I'm working on problem #74 at 4clojure.com, the solution of mine is as following:

(defn FPS [s]
  (->>
    (map read-string (re-seq #"[0-9]+" s))
    (filter #(= (Math/sqrt %) (Math/floor (Math/sqrt %))))
    (interpose ",")
    (apply str)))

It works pretty well. But if I use the "thread-first" macro ->

(defn FPS [s]
  (->
    (map read-string (re-seq #"[0-9]+" s))
    (filter #(= (Math/sqrt %) (Math/floor (Math/sqrt %))))
    (interpose ",")
    (apply str)))

It returns: ClassCastException clojure.lang.LazySeq cannot be cast to clojure.lang.IFn clojure.core/apply (core.clj:617)

Why can "->>" not be replaced by "->" in this problem?

like image 219
Pauli Avatar asked Dec 05 '25 13:12

Pauli


1 Answers

Thread-last macro (->>) inserts each for as the last element of the next form. Thread-first macro (->) inserts it as the second element.

So, this:

(->> a
     (b 1)
     (c 2))

translates to: (c 2 (b 1 a)), while

(-> a
    (b 1)
    (c 2))

translates to: (c (b a 1) 2).

like image 94
Tomo Avatar answered Dec 07 '25 11:12

Tomo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!