How to print each elements of a hash map list using map function in clojure?

匆匆过客 提交于 2019-12-13 06:45:48

问题


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

The following works from the repl only.

(m (map #(hash-map :a %) [1 2 3]))

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?


回答1:


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.

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

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



回答2:


If your goal is simply to call an existing function on every item in a collection in order, ignoring the returned values, then you should use run!:

(run! println [1 2 3])
;; 1
;; 2
;; 3
;;=> nil

In some more complicated cases it may be preferable to use doseq as @Gamlor suggests, but in this case, doseq only adds boilerplate.




回答3:


I recommend to use tail recursion:

(defn printList [a]
  (let [head (first a)
        tail (rest a)]
    (when (not (nil? head))
      (println head)
      (printList tail))))


来源:https://stackoverflow.com/questions/39910297/how-to-print-each-elements-of-a-hash-map-list-using-map-function-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!