gpt4 book ai didi

Clojure:循环访问一个集合的同时循环访问另一个集合?

转载 作者:行者123 更新时间:2023-12-02 14:56:04 27 4
gpt4 key购买 nike

我有两个集合xy,它们都有不同数量的项目。我想循环遍历x并做一些有副作用的事情,同时循环遍历y。我不想在循环 x 时重复 ydoseqfor 都重复 y:

(for [x (range 5)
y ["A" "B"]]
[x y])

这会产生 ([0 "A"] [0 "B"] [1 "A"] [1 "B"] [2 "A"] [2 "B"] [3 "A"] [3“B”] [4“A”] [4“B”])

我想要的是会产生的东西:([0 "A"] [1 "B"] [2 "A"] [3 "B"] [4 "A"]).

背景,我有来自文件和 core.async channel 的行(比如说 5),我想将每一行放入我的集合中的下一个 channel ,例如:

(defn load-data
[file chans]
(with-open [rdr (io/reader file)]
(go
(doseq [l (line-seq rdr)
ch chans]
(>! ch l)))))

最佳答案

如果将多个序列传递给 map ,它会以锁定步骤逐步遍历每个序列,并使用每个序列中当前位置的值调用映射函数。当其中一个序列用完时停止。

user> (map vector (range 5) (cycle ["A" "B"]))
([0 "A"] [1 "B"] [2 "A"] [3 "B"] [4 "A"])

在这种情况下,来自 (cycle ["A""B"]) 的序列将永远持续生成 As 和 B,尽管当来自 (range 5) 的序列时,map 将停止消耗它们) 结束。然后,每个步骤使用这两个参数调用向量函数,并将结果添加到输出序列中。

对于第二个示例,使用 go-loop 是扇出输入序列的相当标准的方法:

user> (require '[clojure.core.async :refer [go go-loop <! <!! >!! >! chan close!]])
nil
user> (defn fanout [channels file-lines]
(go-loop [[ch & chans] (cycle channels)
[line & lines] file-lines]
(if line
(do
(>! ch line)
(recur chans lines))
(doseq [c channels]
(close! c)))))
#'user/fanout
user> (def lines ["first" "second" "third" "fourth" "fifth"])
#'user/lines
user> (def test-chans [(chan) (chan) (chan)])
#'user/test-chans
user> (fanout test-chans lines)
#<ManyToManyChannel clojure.core.async.impl.channels.ManyToManyChannel@3b363fc5>
user> (map <!! test-chans)
("first" "second" "third")
user> (map <!! test-chans)
("fourth" "fifth" nil)

关于Clojure:循环访问一个集合的同时循环访问另一个集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29037732/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com