如何在clojure中使用map函数打印哈希映射列表的每个元素? [英] How to print each elements of a hash map list using map function in clojure?
问题描述
我正在构造一个哈希映射列表,然后将其传递给另一个函数。当我尝试使用 map
从列表中打印每个哈希图时,它不起作用。我可以打印完整列表或获取第一个元素,等等。
I am constructing a list of hash maps which is then passed to another function. When I try to print each hash maps from the list using map
it is not working. I am able to print the full list or get the first element etc.
(defn m [a]
(println a)
(map #(println %) a))
(m (map #(hash-map :a %) [1 2 3]))
但是从我使用 load-file
它不起作用。我看到了 a
,但没有看到它的各个元素。
But from the program that I load using load-file
it is not working. I am seeing the a
but not its individual elements. What's wrong?
推荐答案
在Clojure转换函数中返回惰性序列。因此,(map#(println%)a)
返回一个惰性序列。在使用时,将执行map操作,然后才可以看到打印效果。
In Clojure tranform functions return a lazy sequence. So, (map #(println %) a)
return a lazy sequence. When consumed, the map action is applied and only then the print-side effect is visible.
如果该功能的目的是产生副作用,例如打印,您需要热切地评估转换。函数 dorun 和 doall
If the purpose of the function is to have a side effect, like printing, you need to eagerly evaluate the transformation. The functions dorun and doall
(def a [1 2 3])
(dorun (map #(println %) a))
; returns nil
(doall (map #(println %) a))
; returns the collection
如果您实际上不想映射,但只具有副作用,则可以可以使用 doseq 。旨在重复执行副作用:
If you actually don't want to map, but only have a side effect, you can use doseq. It is intended to 'iterate' to do side effects:
(def a [1 2 3])
(doseq [i a]
(println i))
这篇关于如何在clojure中使用map函数打印哈希映射列表的每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!