31 Jul 2013

Clojure puzzler #1

Which of the following fails and why?
(hash-map (gensym "A") 1 (gensym "B") 2)
(hash-map (gensym) 1 (gensym) 2)
{(gensym "A") 1 (gensym "B") 2}
{(gensym) 1 (gensym) 2}
Hint (hover to reveal): Clojure works by first reading the code into a Clojure data structure and then evaluating it. What does the Clojure reader do when it encounters a map literal? What does (read-string "{(:a) 1 (:a) 2}") do?

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Nice one. I have something similar. Which let binding fails and why? What is returned from the let, after you remove the failing line(s)?

    (let [v ^{:x 2} [1 2 3]
    v ^{'x 2} [1 2 3]
    v ^{x 2} [1 2 3]
    v (read-string "^{x 2} [1 2 3]")
    v ^{x 2} '[1 2 3]
    v '(^{x 2} [1 2 3])]
    (meta (first v)))

    ReplyDelete