Reputation: 135
I have been playing around with clojure for some time.But not able to figure out the difference between ~
vs normal reference
.
For eg:
(defn f [a b] (+ a b))
(f 1 2)
outputs:
3
and on the other hand:
(defn g [a b] `(+ ~a ~b))
(g 1 2)
outputs:
(clojure.core/+ 1 2)
So my question is what's need for different syntax
?
Upvotes: 1
Views: 198
Reputation: 91577
There is a language feature called "syntax-quote" that provides some syntactic shortcuts around forming lists that look like clojure expressions. You don't have to use it to build lists that are clojure s-expressions, you can build what you want with it, though it's almost always used in code that is part of a macro. Where that macro needs to build a Clojure s-expression and return it.
so your example
(defn g [a b] `(+ ~a ~b))
when it's read by the Clojure reader would run the syntax-quote reader macro (which is named `
)
and that syntax-quote macro will take the list
(+ ~a ~b)
as it's argument and return the list
(+ 1 2)
because it interprets symbol ~
to mean "include in the list we are building, the result of evaluating this next thing".
Upvotes: 4
Reputation: 29966
The backquote symbol ` and the tilde ~
are normally only used when writing macros. You shouldn't normally use them when writing normal functions using defn
etc.
You can find more information here and in other books.
Upvotes: 0