【问题标题】:Optimal way to iterate over a core.async channel for printing?迭代 core.async 通道以进行打印的最佳方法?
【发布时间】:2014-10-27 11:49:31
【问题描述】:

我正在尝试将 core.async 通道的结果转储到标准输出。

这是我所拥有的(简化示例):

(use 'clojure.core.async)

(def mychan (to-chan (range 100)))

(loop []
  (let [a (<!! mychan)]
    (if (not (nil? a))
      (do  
        (println a)
        (recur)))))

现在我想我应该可以用地图替换它了:

(map (fn [a] (println a) a) [mychan])

但这似乎很懒惰,并没有返回任何结果。

我不禁觉得我的循环功能在某种程度上是一种解决方法。我的问题是 - 迭代 core.async 通道以进行打印的最佳方式是什么?

【问题讨论】:

    标签: clojure core.async


    【解决方案1】:

    最好使用 go-loop 在 go 块中运行日志记录过程:

    (def c (async/chan 10))
    (go-loop []
      (when-let [msg (<! c)]
        (println msg)
        (recur)))
    (async/onto-chan c (range 100))
    

    或者您可以在 1.7 上使用传感器

    (def prn-chan (async/chan 10 (map println)))
    (async/onto-chan prn-chan (range 100))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 2011-01-20
      • 1970-01-01
      • 2011-12-07
      相关资源
      最近更新 更多