Clojure 中的重复向量
我是 Clojure 新手。我正在尝试获取纸牌套装向量的两份副本。我能想到的非干方式是
(def suits [:clubs :diamonds :hearts :spades])
(def two-times (concat suits suits))
必须有一个更实用的方法方式(即使需要更多字符:-))。如果我想要N次怎么办?有什么建议吗?
我尝试的所有事情,例如
(replicate 2 suits)
产生两个独立向量的结果:
([:clubs :diamonds :hearts :spades] [:clubs :diamonds :hearts :spades])
如何“展平”结构?
I am a Clojure newbie. I am trying to get two copies of a vector of card suits. The non-DRY way that I can come up with is
(def suits [:clubs :diamonds :hearts :spades])
(def two-times (concat suits suits))
There must be a more functional way (even if it takes more characters :-)). What if i want N times? Any suggestions?
All of the things I try, like
(replicate 2 suits)
results in two separate vectors:
([:clubs :diamonds :hearts :spades] [:clubs :diamonds :hearts :spades])
How do I "flatten" the structure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
concat
为您提供了一个惰性序列。如果您想最终得到一个(非惰性)向量:根据您是通过索引大量访问它还是对其进行迭代,向量或 seq 可能更合适。
如果您想要无限(惰性)的重复元素流,也总是有
循环
:concat
gives you a lazy seq. If you want to end up with a (non-lazy) vector instead:Depending whether you're accessing this by index a lot or iterating over it, either a vector or a seq might be more appropriate.
There's always
cycle
too, if you want an endless (lazy) stream of repeated elements:对 REPL 的一些实验让我找到了这个解决方案:
A little experimentation with the REPL lead me to this solution:
(未经测试!)
希望能达到目的。
concat
当然会连接 2 个列表;apply
可用于将给定函数偷运到现有列表的头部位置以进行评估。(untested!)
will hopefully do the trick.
concat
will of course concatenate 2 lists;apply
can be used to smuggle a given function into the head position of an existing list for evaluation.