F # – unpacking / Deconstructing of functional programming


original texthttps://fsharpforfunandprofit.com/posts/overview-of-types-in-fsharp/

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 twoDollarBut they have different meanings and can only be used in different places. firstDollarIt’s one type, and the secondDollarIt’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 themDollarIf 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(Dollar int)Therefore,dThe type of is int

becausedThe 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

  1. The type that defines the parameter isDollarIf you enter an int or other type, an error will be reported to ensure type safety.

  2. Unpacking / deconstruct “by the way” from this parameterDollarThe 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.