Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does List.max<'T> work?

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?
like image 810
missingfaktor Avatar asked May 03 '26 14:05

missingfaktor


1 Answers

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>
like image 155
Random Dev Avatar answered May 05 '26 05:05

Random Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!