Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: What is the meaning of ` and ~@?

Tags:

clojure

I am working through the problems at 4Clojure.

I have a working solution for the Tic-Tac-Toe exercise, but I can't understand Darren's solution:

(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

What is the meaning of ` and ~@?

like image 234
Wieczo Avatar asked Jan 11 '12 01:01

Wieczo


3 Answers

` is the syntax-quote, which is used to write code as data without evaluating it. Note that it is clever enough to resolve symbols that represent functions to the correct namespace.

Examples:

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

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

~@ is the unquote-splicing operator, which will enable you to expand a list of elements within some quoted data/code.

Examples:

(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)

More detail on both of these and related operations can be found as part of the documentation for the Clojure reader.

like image 59
mikera Avatar answered Sep 22 '22 17:09

mikera


See the "Syntax-quote" bullet-pointed section and examples in the documentation on the reader.

like image 32
Alex Taggart Avatar answered Sep 21 '22 17:09

Alex Taggart


Even though it is Common Lisp, and not Clojure, the chapter on macros in Practical Common Lisp has some good examples that translate well:

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

like image 39
TG-T Avatar answered Sep 22 '22 17:09

TG-T