I think this feature is relatively new. I haven’t seen it before. Let’s look at the code first
type Dollar = Dollar of int let earn d:Dollar = d + 10 // Error
Although there are only two lines of code, there are many things worth explaining.
The first line, there are two
DollarBut they have different meanings and can only be used in different places. first
DollarIt’s one type, and the second
DollarIt’s not a type, but a union case. Here, it’s just a deliberate double name, so that the word dollar can be used in both situations.
Therefore, the dollar in the second line of code is a type. In this case, the second line will report an error because the type dollar cannot be added directly to the type int.
Let’s take one of them
DollarIf you change it to another word, you can see it more clearly
type Money = Dollar of int let earn d:Dollar = d + 10 // Error
In this way, because the first dollar has been changed to money, dollar can no longer be used as a type, and the second line will report an error. The reason for this error is “dollar is not a type”.
Look at the following code:
// single case union type Dollar = Dollar of int let earn (Dollar d) = d + 10 // OK
The above code, the second line, uses the new feature I said. The dollar here is not a type, but a union case. At the same time, because union case can be used for pattern match, according to the principle of pattern match,
(Dollar d)It’s a pattern
dThe type of is int
dThe type of is int, so it can be added to 10. This time, the code will not report an error.
It is worth mentioning that the place where pattern match occurs here is the parameter of a function!
What’s more amazing is, here
(Dollar int)It has two functions at the same time
The type that defines the parameter is
DollarIf you enter an int or other type, an error will be reported to ensure type safety.
Unpacking / deconstruct “by the way” from this parameter
DollarThe connotation of data int has been deconstructed.
This paper introduces an interesting feature of F # (unpacking / deconstruction), which looks simple on the surface, but involves the difference between type and union case, as well as the usage of pattern match.