计算Clojure集合的图像包括零值?
(defn image-of
"computes the image of the element x under R"
[R x]
(set
(for [r R]
(when (= (first r) x)
(second r)))))
函数想法:当第一个变量等于x时,将第二个变量添加在r中。
因此,此功能应该计算关系的图像。这有点成功。运行测试时,我会得到以下结果:
输入:(#image of#{[1:a] [2:b] [1:c] [3:a]} 1)
预期:<代码>#{:c:a}
实际:#{nil:c:a}
,因此出于某种原因包括零值。该功能导致了什么?我想我可以滤除任何零值,但希望将解决方案放在一行上。
(defn image-of
"computes the image of the element x under R"
[R x]
(set
(for [r R]
(when (= (first r) x)
(second r)))))
Function idea: Add the second variable in R when it's first is equal to x.
So this function is supposed to compute image of a relation. This is kinda successful. When running a test I get this result:
Input: (image-of #{[1 :a] [2 :b] [1 :c] [3 :a]} 1)
Expected: #{:c :a}
Actual: #{nil :c :a}
So it includes a nil value for some reason. What in the function causes this? I guess I could filter out any nil values but would like to have the solution on a single line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所以问题是我不知道如何使用
when
这个解决方案做到了:
So the problem was I didn't know exactly how to use
when
This solution does it:
让我建议一种不同的方法。
在 Clojure 中表示关系的自然方式是作为从键到值集(或其他集合)的映射。将对的集合转换为这种形式的函数是...
例如,...
您可以将此映射用作函数。如果你给它一个键,它就会返回相应的值:
你可以一次或全部构造这个映射,并根据需要经常使用它。将其作为函数查找实际上是一个常数时间操作。但是每次评估
image-of
时,您都会遍历整个对集合。Let me suggest a different approach.
The natural way to represent a relation in Clojure is as a map from keys to sets (or other collections) of values. A function to convert your collection of pairs to this form is ...
For example, ...
You can use this map as a function. I you feed it a key, it returns the corresponding value:
You construct this map once and or all and use it as often as you like. Looking it up as a function is effectively a constant-time operation. But you run through the entire collection of pairs every time you evaluate
image-of
.