LoginSignup
9
9

More than 5 years have passed since last update.

Clojure のマクロに別名をつける.

Posted at

(def foo ->) は失敗します.


Clojure で内部 DSL を作っているときなど clojure.core のマクロに別名をつけたい場合があります.そんなときに def を使って,(def foo ->) とすると,

user=> (def foo ->)
CompilerException java.lang.RuntimeException: Can't take value of a macro: #'clojure.core/->, compiling:(NO_SOURCE_PATH:1) 

失敗します.-> ではなく var の #'-> であればバインドはできます.

user=> (def foo #'->)
#'user/foo

しかし,この foo はマクロとしては機能しません.

user=> (foo {:a 10} (assoc :b 20))
ArityException Wrong number of args (2) passed to: core$assoc  clojure.lang.AFn.throwArity (AFn.java:437)

ではどのようにすればよいのかというと:

user=> (def ^:macro foo #'->)
#'user/foo

user=> (foo {:a 10} (assoc :b 20))
{:b 20, :a 10}

のように,メタデータで :macrotrue にしてあげればよいのでした.

このノウハウの出典

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9