1
+ //<snippet1>
2
+ open System
3
+ open System.Collections .Generic
4
+
5
+ type Temperature ( kelvins : double ) =
6
+ // The underlying temperature value.
7
+ let mutable kelvins = kelvins
8
+
9
+ do
10
+ if kelvins < 0. then
11
+ invalidArg ( nameof kelvins) " Temperature cannot be less than absolute zero."
12
+
13
+ // Define the is greater than operator.
14
+ static member op_GreaterThan ( operand1 : Temperature , operand2 : Temperature ) =
15
+ operand1.CompareTo operand2 > 0
16
+
17
+ // Define the is less than operator.
18
+ static member op_LessThan ( operand1 : Temperature , operand2 : Temperature ) =
19
+ operand1.CompareTo operand2 < 0
20
+
21
+ // Define the is greater than or equal to operator.
22
+ static member op_GreaterThanOrEqual ( operand1 : Temperature , operand2 : Temperature ) =
23
+ operand1.CompareTo operand2 >= 0
24
+
25
+ // Define the is less than or equal to operator.
26
+ static member op_LessThanOrEqual ( operand1 : Temperature , operand2 : Temperature ) =
27
+ operand1.CompareTo operand2 <= 0
28
+
29
+ member _.Celsius =
30
+ kelvins - 273.15
31
+
32
+ member _.Kelvin
33
+ with get () =
34
+ kelvins
35
+ and set ( value ) =
36
+ if value < 0. then
37
+ invalidArg ( nameof value) " Temperature cannot be less than absolute zero."
38
+ else
39
+ kelvins <- value
40
+
41
+ // Implement the generic CompareTo method with the Temperature
42
+ // class as the Type parameter.
43
+ member _.CompareTo ( other : Temperature ) =
44
+ // If other is not a valid object reference, this instance is greater.
45
+ match box other with
46
+ | null -> 1
47
+ | _ ->
48
+ // The temperature comparison depends on the comparison of
49
+ // the underlying Double values.
50
+ kelvins.CompareTo( other.Kelvin)
51
+
52
+ interface IComparable< Temperature> with
53
+ member this.CompareTo ( other ) = this.CompareTo other
54
+
55
+ let temps = SortedList()
56
+
57
+ // Add entries to the sorted list, out of order.
58
+ temps.Add( Temperature 2017.15 , " Boiling point of Lead" )
59
+ temps.Add( Temperature 0. , " Absolute zero" )
60
+ temps.Add( Temperature 273.15 , " Freezing point of water" )
61
+ temps.Add( Temperature 5100.15 , " Boiling point of Carbon" )
62
+ temps.Add( Temperature 373.15 , " Boiling point of water" )
63
+ temps.Add( Temperature 600.65 , " Melting point of Lead" )
64
+
65
+ for kvp in temps do
66
+ printfn $" {kvp.Value} is {kvp.Key.Celsius} degrees Celsius."
67
+
68
+ // This example displays the following output:
69
+ // Absolute zero is -273.15 degrees Celsius.
70
+ // Freezing point of water is 0 degrees Celsius.
71
+ // Boiling point of water is 100 degrees Celsius.
72
+ // Melting point of Lead is 327.5 degrees Celsius.
73
+ // Boiling point of Lead is 1744 degrees Celsius.
74
+ // Boiling point of Carbon is 4827 degrees Celsius.
75
+ //</snippet1>
0 commit comments