List.max<'T> 如何实现工作?
从MSDN文档来看,List.max
的签名是:
List.max : 'T list -> 'T (requires comparison)
我的问题是:
- 编译器如何静态验证
'T
支持比较操作? -
requires
是指定类型约束的关键字吗?如果是,我可以用它指定哪些类型的约束? - 我可以定义自己的约束类型吗,就像我可以在 Scala 中使用类型类那样?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看一下 Don Syme 的博客:F# 中的相等和比较约束
通常,您可以将这些约束视为轻型类型类的一种形式在这种情况下,重写 Equals/GetHashCode 并实现 IComparable 足以使用它。
对于您的问题:
PS:(需要比较)是通过说
<'a 当 'a 时定义的: 比较>
在通用定义的上下文中,例如take a look at this blog from Don Syme: Equality and Comparison Constraints in F#
you can think of those contraints as a form of type-classes light, normaly overriding Equals/GetHashCode and implementing IComparable is sufficient to use it in this cases.
To your questions:
PS: the (requires comparison) is defined by saying
<'a when 'a : comparison>
in the context of a generic definition like卡斯滕的回答涵盖了大部分基础。关于声明约束,在大多数情况下,您不需要声明它,因为它会通过使用比较运算符来推断。例如:
正如 Carsten 所说,如果你想用约束显式注释定义,你可以这样做:
Carsten's answer covers most of the bases. Regarding declaring the constraint, in most cases you don't need to declare it since it will be inferred by any use of a comparison operator. For instance:
As Carsten said, if you want to explicitly annotate the definition with the constraint you can do it like this: