why does clojure's map println only works in repl?

前提是你 提交于 2019-12-20 05:45:32

问题


I use lein new app test-println to create a clojure app and launch the repl with lein repl, then I enter (map println [1 2 3 4 5 6]) and get the expected result: test-println.core=> (map println [1 2 3 4 5 6]) 1 2 3 4 5 6 (nil nil nil nil nil nil)

However if I add (map println [1 2 3 4 5 6]) to the end of src/test_println/core.clj:

(ns test-println.core
  (:gen-class))

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (println "Hello, World!")
  (map println [1 2 3 4 5 6]))

lean run prints only Hello, World!.


回答1:


map is lazy. To quote the first sentence of the documentation (emphasis added):

Returns a lazy sequence consisting of the result of applying f to the set of first items of each coll, followed by applying f to the set of second items in each coll, until any one of the colls is exhausted.

The REPL forces evaluation of the expression to show the result, but nothing in your code does. dorun would solve this, but you probably should look at doseq / doall instead.




回答2:


If your goal is to run a single procedure over every item in a single collection, you should use run!:

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

In cases where the action you need to perform on each collection is more complex than simply applying an existing function, doseq may be more convenient, but run! is a better choice here.



来源:https://stackoverflow.com/questions/39070972/why-does-clojures-map-println-only-works-in-repl

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