计算Clojure集合的图像包括零值?

发布于 2025-01-18 04:44:31 字数 445 浏览 2 评论 0原文

 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千纸鹤 2025-01-25 04:44:31

所以问题是我不知道如何使用 when
这个解决方案做到了:

(set (for [r R 
           :when (= (first r) x)] 
       (second r)))

So the problem was I didn't know exactly how to use when
This solution does it:

(set (for [r R 
           :when (= (first r) x)] 
       (second r)))
一身骄傲 2025-01-25 04:44:31

让我建议一种不同的方法。

在 Clojure 中表示关系的自然方式是作为从键到值集(或其他集合)的映射。将对的集合转换为这种形式的函数是...

(defn pairs->map [pairs]
  (reduce
    (fn [acc [key value]]
      (assoc acc key (conj (acc key #{}) value)))
    {}
    pairs))

例如,...

(pairs->map #{[1 :a] [2 :b] [1 :c] [3 :a]})
=> {2 #{:b}, 1 #{:c :a}, 3 #{:a}}

您可以将此映射用作函数。如果你给它一个键,它就会返回相应的值:

({2 #{:b}, 1 #{:c :a}, 3 #{:a}} 1)
=> #{:c :a}

你可以一次或全部构造这个映射,并根据需要经常使用它。将其作为函数查找实际上是一个常数时间操作。但是每次评估 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 ...

(defn pairs->map [pairs]
  (reduce
    (fn [acc [key value]]
      (assoc acc key (conj (acc key #{}) value)))
    {}
    pairs))

For example, ...

(pairs->map #{[1 :a] [2 :b] [1 :c] [3 :a]})
=> {2 #{:b}, 1 #{:c :a}, 3 #{:a}}

You can use this map as a function. I you feed it a key, it returns the corresponding value:

({2 #{:b}, 1 #{:c :a}, 3 #{:a}} 1)
=> #{:c :a}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文