3
votes

I have a function which generates a vector of coordinates in a square board. The result of running this function is something of the form

 [{:x 1, :y 0} {:x 0, :y 1} {:x 2, y:3} {:x 3, :y 4}]

After running this function, I need to apply another function to the result above. Since I'd be mapping a function over a collection, I thought using the map function would be appropriate. As such, I wrote the following method:

(defn attack [x y] (map (fn [coord] (println (get coord :x))) [{:x 1, :y 0} {:x 0, :y 1}]))

(I've also tried the example above with get-in instead of get, to no avail)

This is not the final form of the method, and instead is just something I tried to see if I could at least see something printed to the terminal after running

clojure myscript.clj

However, nothing comes out of it and it doesn't seem to matter whether I return a value from the fn function or not. For example, this

(defn attack [x y] (map (fn [coord] coord) [{:x 1, :y 0} {:x 0, :y 1}]))

also returns nothing. Does anyone know how I could at least get access to the values inside the vector in my fn function?

Lastly, does it matter whether my vector is generated by a call to another function?
For example,

(defn attack [x y] (map (fn [coord] coord) (get-attack-coordinates x y)))

would this be a problem? I'm guessing not, but I thought it was a good idea to ask just in case. Thank you all for reading :)

2

2 Answers

3
votes

map does return in this case

(map (fn [coord] coord) [{:x 1, :y 0} {:x 0, :y 1}])
;; => ({:x 1, :y 0} {:x 0, :y 1})

Note that in this case:

(map (fn [coord] (println (get coord :x))) [{:x 1, :y 0} {:x 0, :y 1}])

It will first print 1 and then 0 and then return

(nil nil)

because println returns nil.

Furthermore, if you want access to the x and y you can also use destructuring:

(map (fn [{:keys [x y]}] [x y]) [{:x 1, :y 0} {:x 0, :y 1}])

Note that I tried these things in the REPL:

The REPL

3
votes

(map f xs) always returns something. It's impossible not to. If you think it doesn't, there's something wrong with how you're measuring, not with your map call. Include more code about the structure of your program, not just this one snippet.