Does 'concat' break the laziness of 'line-seq'?

杀马特。学长 韩版系。学妹 提交于 2019-12-11 07:07:33

问题


The following code appears to force line-seq to read 4 lines from file. Is this some kind of buffering mechanism? Do I need to use lazy-cat here? If so, how can I apply a macro to a sequence as if it were variadic arguments?

(defn char-seq [rdr]
  (let [coll (line-seq rdr)]
    (apply concat (map (fn [x] (println \,) x) coll))))

(def tmp (char-seq (clojure.contrib.io/reader file)))

;,
;,
;,
;,
#'user/tmp

回答1:


Part of what you're seeing is due to apply, since it will need to realize as many args as needed by the function definition. E.g.:

user=> (defn foo [& args] nil)
#'user/foo
user=> (def bar (apply foo (iterate #(let [i (inc %)] (println i) i) 0)))
1
#'user/bar
user=> (defn foo [x & args] nil)
#'user/foo
user=> (def bar (apply foo (iterate #(let [i (inc %)] (println i) i) 0)))
1
2
#'user/bar
user=> (defn foo [x y & args] nil)
#'user/foo
user=> (def bar (apply foo (iterate #(let [i (inc %)] (println i) i) 0)))
1
2
3
#'user/bar


来源:https://stackoverflow.com/questions/4290665/does-concat-break-the-laziness-of-line-seq

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