Mohammed Amarnah
Mohammed Amarnah

Reputation: 85

accessing Clojure's thread-first macro arguments

I was wondering if there was a way to access the arguments value of a thread-first macro in Clojure while it is being executed on. for example:

(def x {:a 1 :b 2})
(-> x
    (assoc :a 20) ;; I want the value of x after this step
    (assoc :b (:a x))) ;; {:a 20, :b 1}

It has come to my attention that this works:

(-> x 
    (assoc :a 20) 
    ((fn [x] (assoc x :b (:a x))))) ;; {:a 20, :b 20}

But are there any other ways to do that?

Upvotes: 7

Views: 309

Answers (2)

Nico Schneider
Nico Schneider

Reputation: 106

In addition to akond's comment, note that using as-> can get quite confusing quickly. I recommend either extracting a top level function for these cases, or trying to use as-> in -> only:

(-> something
    (process-something)
    (as-> $ (do-something $ (very-complicated $)))
    (finish-processing))

Upvotes: 1

akond
akond

Reputation: 16035

You can use as->:

(let [x {:a 1 :b 2}]
    (as-> x it
        (assoc it :a 20)                                             
        (assoc it :b (:a it)))) 

Upvotes: 10

Related Questions