为什么支持基于(看似)任意规则的不同数据类型之间的比较?

发布于 2024-10-24 05:45:38 字数 1059 浏览 2 评论 0原文

我的问题是,“为什么语言设计者会考虑允许不同数据类型之间的比较?”。另外,这在函数式语言中更有意义吗?

例如,在 erlang 中可以执行以下比较:

%% Tuples are greater than numbers
999999 < {1,2}.
true

%% Lists are greater than tuples
{90000} < [1].
true

%% Atoms are greater than numbers
1 < false.
true

在 python 2.x 中也是如此,

p = lambda x,y: x+y

p > (1)
True

p < (1)
False

p == (1)
False

尽管看起来 python 社区认为这毕竟不是一个好主意:

总是不同类型的对象 比较不相等,并排序 一致但任意。 [...] 这种不同寻常的比较定义 用于简化定义 排序等操作以及 in 和 不在运营商中。 来源

来自 Python 3 发行说明:

排序比较运算符 (<, <=、>=、>) 引发 TypeError 异常 当操作数没有 有意义的自然排序。因此, 表达式如 1 < '',0>无或 len <= len 不再有效,并且 例如无<没有引发类型错误 而不是返回 False。一个 推论是排序 a 异构列表不再使 意义——所有元素都必须是 彼此具有可比性。 来源

这解释了原因,但我想知道是否有还有其他原因允许这样做,特别是在函数式语言中。

My questions is, "Why would a language designer consider allowing comparison between different data types?". Also, does this make more sense in a functional language?

For example, in erlang one can perform the following comparisons:

%% Tuples are greater than numbers
999999 < {1,2}.
true

%% Lists are greater than tuples
{90000} < [1].
true

%% Atoms are greater than numbers
1 < false.
true

In python 2.x as well,

p = lambda x,y: x+y

p > (1)
True

p < (1)
False

p == (1)
False

Though looks like the python community decided this wasn't a good idea after all:

objects of different types always
compare unequal, and are ordered
consistently but arbitrarily.
[...]
This unusual definition of comparison
was used to simplify the definition of
operations like sorting and the in and
not in operators.
source

From the Python 3 release note:

The ordering comparison operators (<,
<=, >=, >) raise a TypeError exception
when the operands don’t have a
meaningful natural ordering. Thus,
expressions like 1 < '', 0 > None or
len <= len are no longer valid, and
e.g. None < None raises TypeError
instead of returning False. A
corollary is that sorting a
heterogeneous list no longer makes
sense – all the elements must be
comparable to each other.
source

This kind of explains why, but I was wondering if there are other reasons to allow this, particularly in functional languages.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

挽袖吟 2024-10-31 05:45:39

在动态语言中,它具有一定的意义,因为能够对异构列表进行排序并构建异构树是很好的。我想我会说,与其说是函数式语言,不如说是强类型语言,原因很明显。

In dynamic languages it makes a certain amount of sense, as it's nice to be able to sort heterogeneous lists and build heterogeneous trees. And I think I would say that it's not so much functional languages where it's dubious as it is strongly typed languages, for obvious reasons.

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