On Thu, Jul 5, 2012 at 10:11 AM, Jacobo Polavieja
<jacobopolavi...@gmail.com> wrote:
>> (defn neighbors
>>     ([size yx] (neighbors [[-1 0] [1 0] [0 -1] [0 1]] size yx))
>>     ([deltas size yx]
>> (filter (fn [new-yx]
>>
>>             (every? #(< -1 % size) new-yx)) (map #(map + yx %) deltas))))

Let's take your second question first:

> 2. I also don't understand which value that '%' refers to inside de every?
> and what exactly that  #(< -1 % size) new-yx)) does, although it should be
> pretty simple.

#(...) is an anonymous function where % refers to the implied
argument, so the above could be rewritten as follows:

#(< -1 % size) ;; => (fn [n] (< -1 n size))

#(map + yx %) ;; => (fn [d] (map + yx d))

> 1. What is the value of that [new-yx] ?

It's an argument to the anonymous function passed to the filter function:

(filter (fn [new-yx] ...) ...)

You could define those anonymous functions outside neighbors and get
the same effect but they are closures over local variables (size, yx)
so you'd need to use partial or functions that return functions:

(defn in-range? [lo hi x] (< lo x hi))

(defn all-in-range [lo hi values] (every? (partial in-range lo hi) values))

(defn inc-by [n x] (+ n x))

(defn inc-all-by [n xs] (map (partial inc-by n) xs))

(defn neighbors
    ([size yx] ...)
    ([deltas size yx]
        (filter (partial all-in-range -1 size)
            (map (partial inc-all-by yx) deltas))))

Not sure if that is easier to follow or not?

(hopefully I got that transformation correct - I didn't test it!)

> 3. More or less the same with the last two "map". I don't know why it
> shouldn't suffice with something like (map #(+ yx %) deltas).

Because deltas is a nested sequence - a vector of vectors (a 2D
matrix) - so the outer map applies the function argument to each
nested vector and therefore the inner map applies its function
argument to each element of that nested vector.

It may help to think of map being like a loop in an imperative
language so (map #(map f %) matrix) is like a pair of nested loops
that ultimately applies f to every element of the matrix.

Hope that helps?
-- 
Sean A Corfield -- (904) 302-SEAN
An Architect's View -- http://corfield.org/
World Singles, LLC. -- http://worldsingles.com/

"Perfection is the enemy of the good."
-- Gustave Flaubert, French realist novelist (1821-1880)

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