Kapol
Kapol

Reputation: 6463

Why are parenthesis required when using members of union type bound to `let`?

Having the following type:

type MyType =
    | MyType of string

I tried to do this:

let myFunc x =
    let MyType y = x
    y // Compilation error

This causes a compilation error:

The value or constructor y is not defined.

However, if I put parenthesis around MyType y, the code compiles.

let myFunc x =
    let (MyType y) = x
    y // Compiles successfully

What is the difference between the two versions?

Upvotes: 2

Views: 55

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80734

The first version declares a function named MyType with one parameter named y. This parameter is only available in the body of this function, so you get an error when you try to access this parameter outside of the function.

The second version destructures a value with constructor named MyType, binding its content to identifier y. This identifier is then available until the current scope ends.

The parentheses as necessary to distinguish destructuring from function declaration.

In this particular case you can simplify the destructuring by moving it into the parameter list:

let myFunc (MyType y) =
    y

Upvotes: 5

Related Questions