简体   繁体   English

如何在clojure中的地图向量上使用map函数

[英]How to use the map function on a vector of maps in clojure

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.由于我将在集合上映射函数,因此我认为使用 map 函数是合适的。 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) (我也试过上面的例子,用 get-in 而不是 get,但无济于事)

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.但是,它没有任何结果,我是否从 fn 函数返回一个值似乎并不重要。 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?有谁知道我如何至少可以访问 fn 函数中向量内的值?

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 :)谢谢大家阅读:)

(map f xs) always returns something. (map f xs)总是会返回一些东西。 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.如果您认为没有,那么您的测量方式有问题,而不是您的map调用有问题。 Include more code about the structure of your program, not just this one snippet.包括更多关于程序结构的代码,而不仅仅是这一个片段。

map does return in this case在这种情况下, map确实会返回

(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它会先打印 1 然后打印 0 然后返回

(nil nil)

because println returns nil .因为println返回nil

Furthermore, if you want access to the x and y you can also use destructuring :此外,如果您想访问xy您还可以使用解构

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

Note that I tried these things in the REPL:请注意,我在 REPL 中尝试了这些东西:

REPL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM