List.max<'T> 如何实现工作?

发布于 2024-12-04 12:05:58 字数 298 浏览 4 评论 0 原文

从MSDN文档来看,List.max的签名是:

List.max : 'T list -> 'T (requires comparison)

我的问题是:

  • 编译器如何静态验证'T支持比较操作?
  • requires 是指定类型约束的关键字吗?如果是,我可以用它指定哪些类型的约束?
  • 我可以定义自己的约束类型吗,就像我可以在 Scala 中使用类型类那样?

From MSDN docs, the signature of List.max is:

List.max : 'T list -> 'T (requires comparison)

My questions are:

  • How does compiler statically verify that 'T supports comparison operation?
  • Is requires a keyword to specify type constraints? If yes, what all types of constraints can I specify with it?
  • Can I define my own kinds of constraints, like I can do with typeclasses in Scala?

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

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

发布评论

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

评论(2

凉世弥音 2024-12-11 12:05:58

看一下 Don Syme 的博客:F# 中的相等和比较约束

通常,您可以将这些约束视为轻型类型类的一种形式在这种情况下,重写 Equals/GetHashCode 并实现 IComparable 足以使用它。

对于您的问题:

  1. 是的,编译器会
  2. 准确地检查这一点,请查看 F# 规范 / Docu 了解更多详细信息
  3. - 您可以限制接口等 - 请参阅文章

PS:(需要比较)是通过说 <'a 当 'a 时定义的: 比较> 在通用定义的上下文中,例如

type MyType<'a when 'a : comparision>

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:

  1. yes the compiler will check this
  2. yes exactly, look at the F# specifications / Docu for more details
  3. kind of - you can contraint to interfaces and that like - see the articles

PS: the (requires comparison) is defined by saying <'a when 'a : comparison> in the context of a generic definition like

type MyType<'a when 'a : comparision>
り繁华旳梦境 2024-12-11 12:05:58

卡斯滕的回答涵盖了大部分基础。关于声明约束,在大多数情况下,您不需要声明它,因为它会通过使用比较运算符来推断。例如:

let myListMax l = l |> List.reduce (fun x y -> if x > y then x else y)
// or myListMax l = l |> List.reduce max

正如 Carsten 所说,如果你想用约束显式注释定义,你可以这样做:

let myListMax (l:'a list) : 'a when 'a : comparison = l |> List.reduce max

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:

let myListMax l = l |> List.reduce (fun x y -> if x > y then x else y)
// or myListMax l = l |> List.reduce max

As Carsten said, if you want to explicitly annotate the definition with the constraint you can do it like this:

let myListMax (l:'a list) : 'a when 'a : comparison = l |> List.reduce max
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文