Clojure:`和〜@是什么意思?

时间:2012-01-11 01:04:17

标签: clojure

我正在处理problems at 4Clojure

我有Tic-Tac-Toe exercise的工作解决方案,但我无法理解Darren's解决方案:

(fn [b]
  (some (fn [p] (first (keep #(if (apply = p %) p)
                         `(~@b                   ; <- What is that ` and ~@?
                           ~@(apply map list b)  ; 
                           ~(map get b [0 1 2])
                           ~(map get b [2 1 0])))))
     [:x :o]))
 ;b is a two-dimensional vector

`和〜@?

是什么意思

3 个答案:

答案 0 :(得分:11)

`是语法引用,用于将代码编写为数据而不进行评估。请注意,它足够聪明,可以将表示函数的符号解析为正确的命名空间。

示例:

`(+ 1 2)
=> (clojure.core/+ 1 2)    ; a list containing the + function and two arguments

(eval `(+ 1 2))
=> 3                       ; the result of evaluating the list

〜@是非引用拼接运算符,它可以让您扩展某些引用数据/代码中的元素列表。

示例:

(def args [3 4 5 6])

`(+ 1 2 ~@args 7 8)
=> (clojure.core/+ 1 2 3 4 5 6 7 8)

`(+ ~@(range 10))
=> (clojure.core/+ 0 1 2 3 4 5 6 7 8 9)

有关这些操作和相关操作的更多详细信息,请参阅documentation for the Clojure reader

答案 1 :(得分:2)

请参阅documentation on the reader中的“语法 - 引用”子弹头部分和示例。

答案 2 :(得分:2)

即使它是Common Lisp,而不是Clojure,实用Common Lisp中关于宏的章节有一些很好的例子可以很好地转换:

http://www.gigamonkeys.com/book/macros-defining-your-own.html

相关问题