Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a clojure map threading macro ( map-> )

Tags:

clojure

I'm inspired by clojure's 1.5 cond-> macro.

Similarily, I want to create a macro of the same idea, applied to the function map. However, I have no idea where to start.

For example, I can't find the source for cond->. (probably because it's not released yet)

Any suggestions?

like image 596
Zchpyvr Avatar asked Apr 19 '26 11:04

Zchpyvr


2 Answers

There is the source of cond-> https://github.com/clojure/clojure/blob/master/src/clj/clojure/core.clj#L6742

like image 108
mobyte Avatar answered Apr 23 '26 00:04

mobyte


there are a variety of threading macros from the pallet project folks including apply-map-> which looks close to, though not exactly what you are looking for.

(letfn [(apply-map-
          [arg f arg-coll]
          `(let [arg# ~arg]
             (apply ~f arg#
                    ~@(butlast arg-coll)
                    (apply concat ~(last arg-coll)))))]

  (defmacro apply-map->
    "Apply in a threaded expression.
   e.g.
      (-> :a
        (apply-map-> hash-map 1 {:b 2}))
   => {:a 1 :b 2}"
    [arg f & arg-coll]
    (apply-map- arg f arg-coll))

Perhaps there will be enough examples there for you to pick out what you need.

like image 33
Arthur Ulfeldt Avatar answered Apr 22 '26 23:04

Arthur Ulfeldt