集合与序列的Clojure等式 [英] Clojure equality of collections with sequences

查看:55
本文介绍了集合与序列的Clojure等式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到Clojure(1.4)似乎很乐意考虑等于相同向量的 seq 的向量,但是相同的不适用于地图:

I noticed that Clojure (1.4) seems to be happy to consider vectors equal to the seq of the same vector, but that the same does not apply for maps:

(= [1 2] (seq [1 2]))
=> true

(= {1 2} (seq {1 2}))
=> false

为什么 = 的行为应为

推荐答案

Clojure的 = 可以认为是分两步执行比较:

Clojure's = can be thought of as performing its comparisons in two steps:


  1. 检查所比较事物的类型是否属于相同的平等分区,那是一类类型,其成员可能相等(取决于像给定数据结构的确切成员之类的东西,但不取决于分区中的特定类型);

  1. Check if the types of the things being compared belong to the same "equality partition", that is a class of types whose members might potentially be equal (depending on things like the exact members of a given data structure, but not the particular type in the partition);

如果是这样,请检查所比较的事物是否实际上相等。

If so, check if the things being compared actually are equal.

一个这样的相等分区是: 顺序事物。向量被认为是顺序的:

One such equality partition is that of "sequential" things. Vectors are considered sequential:

(instance? clojure.lang.Sequential [])
;= true

各种类型的序列如下:

(instance? clojure.lang.Sequential (seq {1 2}))
;= true

因此,当(且仅当)其对应元素相等时,向量才被视为等于序列。

Therefore a vector is considered equal to a seq if (and only if) their corresponding elements are equal.

(请注意,(seq {})产生 nil ,这是 not 顺序的,并且比较不等于 () [] 等)

(Note that (seq {}) produces nil, which is not sequential and compares "not equal" to (), [] etc.)

在另一方面,映射构成它们自己的相等分区,因此,虽然哈希映射可能被视为等于排序的映射,但永远不会将其视为等于序列。特别是,它不等于其条目的seq,这就是(seq some-map)产生的。

On the other hand, maps constitute an equality partition of their own, so while a hash map might be considered equal to a sorted map, it will never be considered equal to a seq. In particular, it is not equal to the seq of its entries, which is what (seq some-map) produces.

这篇关于集合与序列的Clojure等式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆