基本上,我有一个集合向量。我想根据某个条件合并集合(您可以在 if 语句中看到此条件)。可以合并两个以上的集合。这是一个示例数据集:
[{:name "corner", :matched-shape "corner", :direction :e, :rotation 1}
{:name "corner", :matched-shape "corner", :direction :e, :rotation 2}
{:name "corner", :matched-shape "corner", :direction :s, :rotation 2}
{:name "corner", :matched-shape "corner", :direction :s, :rotation 3}
{:name "corner", :matched-shape "pipe", :direction :s, :rotation 0}
{:name "corner", :matched-shape "pipe", :direction :e, :rotation 1}
{:name "corner", :matched-shape "pipe", :direction :s, :rotation 2}
{:name "corner", :matched-shape "pipe", :direction :e, :rotation 3}
{:name "corner", :matched-shape "cross", :direction :e, :rotation 0}
{:name "corner", :matched-shape "cross", :direction :s, :rotation 0}
{:name "corner", :matched-shape "cross", :direction :e, :rotation 1}
{:name "corner", :matched-shape "cross", :direction :s, :rotation 1}]
我尝试了数十种解决方案,但没有一个有效。这是我的代码:
(defn merge-symmetry-table [symmetry-table]
(filter #(if-not (nil? %) %)
(loop [[x y & remaining] symmetry-table result []]
(if-not (empty? y)
(if (and (= (:name x) (:name y))
(= (:direction x) (:direction y)))
(recur [(concat-symmetries x y) remaining] result)
(recur [conj y remaining] [result x]))
(conj result x)))))
以及我现在的输出:
([]
{:name "corner", :direction :e, :matched-shapes ["corner" 1 "corner" 2]}
{:name nil, :direction nil, :matched-shapes [[nil nil nil nil] nil nil]})
我确信有更好的方法可以做到这一点,但我想知道我的代码到底出了什么问题。我已经看了五十遍了,但我不明白哪里出了问题。谢谢您的帮助。
我不确定我是否可以在这里表达不满(我不想打扰任何人),但我在用这种编程语言处理数据时遇到了绝对巨大的困难。诚然,这是我用这种语言的第一个项目,而且我主要是一个自学成才的程序员。但是,将向量嵌套在向量中并仅使用“键映射”使得尝试完成任何事情都成为一场绝对的噩梦,更不用说以一种有凝聚力的方式组织数据了。我可能会重写我的函数至少十次,只是为了让它们返回我想要的结果。一定是我漏掉了什么。
您可能想使用
partition-by
:
(->> data
(partition-by (juxt :name :direction))
(map (partial apply concat-symmetries)))
或
group-by
:
(->> data
(group-by (juxt :name :direction))
vals
(map (partial apply concat-symmetries)))