Bytesource wrote:
I am currently reading "Programming Clojure" but got stuck at the
destructuring done in the "head-overlaps-body?" function call that is
part of the "snake" game:

(defn head-overlaps-body? [{[head & body] :body}]
  (includes? body head))

;; page 200 of the pdf version

I can not figure out what {[head & body] :body} actually means here.

Some simple examples might help -

(def snake {:body [[1 2] [2 3] [4 5] [6 4]]})

So snake is a map which has the key :body whose value is a vector of vectors.

user> (def body-vals (:body snake))
[[1 2] [2 3] [4 5] [6 4]]

The first vector in body-vals is the actual head and the rest is the body.

user> (def head (first body-vals)
[1 2]

user> (def body (rest body-vals)
[2 3] [4 5] [6 4]

Now that we have separated out the data, we can proceed and use them in our functions.

But then, that's a bit too much of code, since we can "destructure" the snake very easily in the function args part like this -

[{[head & body] :body}]

What it does is that it first extracts the value of the :body key in the map which is passed to the function.

Since the value of :body is supposed to be a vector, we can destructure it further into head and body.

You can do the same kind of destructuring in a let form too.

I hope I was able to explain it to you. I agree, the examples were pretty lame :)

Regards,
BG

--
Baishampayan Ghose <b.gh...@ocricket.com>

--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to