Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 866
Mohammed Amarnah Avatar asked Jan 15 '19 10:01

Mohammed Amarnah


2 Answers

You can use as->:

(let [x {:a 1 :b 2}]
    (as-> x it
        (assoc it :a 20)                                             
        (assoc it :b (:a it)))) 
like image 116
akond Avatar answered Nov 26 '22 04:11

akond


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))
like image 38
Nico Schneider Avatar answered Nov 26 '22 04:11

Nico Schneider