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 ~@?
` 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.
See the "Syntax-quote" bullet-pointed section and examples in the documentation on the reader.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With