clojure for 循环,将值存储在集合或映射中
这个问题困扰我有一段时间了 我们应该如何在 for 循环中将值存储在集合或映射中?
(let [s #{}]
(for [ i (range 10)
j (range 10) ]
(into s [i j])))
我知道这行不通,但我想要一个与此类似的功能,其中该集合最终将包含 [0 0] [0 1]...[0 9] [1 0]...[9 9]
谢谢
This one has been bothering me for a while now,
How should we store a value in a set or map in a for loop?
(let [s #{}]
(for [ i (range 10)
j (range 10) ]
(into s [i j])))
i know this will not work, but i want a functionality similar to this , where the set will finally contain [0 0] [0 1]...[0 9] [1 0]...[9 9]
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果我正确理解你的问题,你需要把你的表达从里到外:
这里要意识到的是
for
返回一个值(惰性序列),与 Java 和 C 等命令式语言中的 for 循环不同。If I understand your question correctly you need to turn your expression inside-out:
The thing to realize here is that
for
returns a value (a lazy sequence) unlike for-loops in more imperative languages like Java and C.这是你想要的吗?
如果您只想将列表作为一组:
您最终会得到一组对。
Is this what you want?
And if you just want the list as a set:
You will end up with a set of pairs.
通常当您想要从 seq 上的“重复”广义操作返回一个集合、映射或其他不是 seq 的“单值”时,请使用
reduce
比loop/recur
更惯用/直接,并且for
总是返回一个seq(而不是一个集合或映射)。请注意,(for ..) 此处仅用于生成一个包含所有要编译到单个结果集中的值的 seq。或者,例如:
Generally when you want to return a set or a map or other 'single value' that isn't a seq from a 'repeated' generalized operation on a seq, using
reduce
is more idiomatic/straightforward thanloop/recur
, andfor
always returns a seq (not a set or map).note that (for ..) here is only used to produce a seq containing all the values to compile into the single result set. Or, for example:
clojure 有几个很棒的系统来管理可变状态。在这种情况下,您可能需要一个 atom 包含一组
其他选项:
for
已经异步返回一个序列,所以你可能只想
clojure has a several great systems for managing mutable state. in this case you may want an atom containing a set
your other options are:
of course
for
returns a sequence already so you may just want我认为在这种情况下你也可以使用一些瞬态数据结构。
只是代码示例,未经测试。
I think you can also use some transient data structure in this scenario.
Just a code sample, not tested.