为什么支持基于(看似)任意规则的不同数据类型之间的比较?
我的问题是,“为什么语言设计者会考虑允许不同数据类型之间的比较?”。另外,这在函数式语言中更有意义吗?
例如,在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在动态语言中,它具有一定的意义,因为能够对异构列表进行排序并构建异构树是很好的。我想我会说,与其说是函数式语言,不如说是强类型语言,原因很明显。
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.