简体   繁体   中英

Clojure Sort-by inside macro

i need to do a sort-by inside a macro, i have a map set like this:

(def persons '({:id 1 :name "olle"} {:id 2 :name "anna"} {:id 3 :name "isak"} {:id 4 :name "beatrice"}))

if i try to do (sort-by :name persons) it works fine and sort it

but within the macro:

(defmacro select
  [columns _ map _ where _ order]
  `(sort-by ~order ~@map))

it doesnt sort.

REPL (clojure.core/sort-by :name persons)

You've got an error in ~@map clause. You do not need @ here. That symbol expands a sequence in place, eg [1 2 3] -> 1 2 3 .

The working code:

(defmacro select
  [columns _ map _ where _ order]
  `(sort-by ~order ~map))

Check with expanding the macro:

(macroexpand '(select nil nil persons nil nil nil :id))
(clojure.core/sort-by :id persons)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM