〜'或'〜在Clojure的目的是什么? [英] What is the purpose of ~' or '~ in Clojure?

查看:102
本文介绍了〜'或'〜在Clojure的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Clojure宏,代码示例有时会有'〜符号或者〜'符号。我知道(quote '阻止评估表单,反引号另外添加了命名空间限定,我的问题是:为什么停止然后开始评估是有用的?我还假设〜'符号

I am learning about Clojure macros, and the code examples will sometimes have the constructs '~symbol or alternately ~'symbol. I know that (quote and ' prevent a form from being evaluated, and that the backquote additionally adds namespace qualification, and that ~ causes a quoted form to be evaluated. My question is: why is it useful to stop then start evaluation? I also assume that ~'symbol and '~symbol are different, but how so?

推荐答案

〜 '符号用于产生一个非限定符号。默认情况下,Clojure的宏捕获命名空间,因此宏中的符号通常被解析为 -namespace / symbol)。unquote-quote idiom直接导致简单的,无限定的符号名称 - (symbol)从Clojure的喜悦:

~'symbol is used to produce an unqualified symbol. Clojure's macros capture namespace by default, so a symbol in a macro would normally be resolved to (your-namespace/symbol). The unquote-quote idiom directly results in the simple, unqualified symbol name - (symbol) - by evaluating to a quoted symbol. From The Joy Of Clojure:

(defmacro awhen [expr & body]
  `(let [~'it ~expr] ; refer to the expression as "it" inside the body
    (when ~'it
      (do ~@body))))

(awhen [:a :b :c] (second it)) ; :b

'〜符号在宏中插入名称或类似的东西。这里,符号将绑定到一个值 - let [symbol'my-symbol] 。然后,通过评估符号将此值插入到代码中。

'~symbol is likely used to insert a name in the macro or something similar. Here, symbol will be bound to a value - let [symbol 'my-symbol]. This value is then inserted into the code the macro produces by evaluating symbol.

(defmacro def-symbol-print [sym]
  `(defn ~(symbol (str "print-" sym)) []
    (println '~sym))) ; print the symbol name passed to the macro

(def-symbol-print foo)
(print-foo) ; foo

这篇关于〜'或'〜在Clojure的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆