How to destroy a constructor argument?

In F #, I can use pattern matching in many places inside the syntax.

For instance:

// Given this type... type SingleCaseUnion = | SingleCaseUnion of int /// ...I can do this: let destructureInFunc (SingleCaseUnion n) = printfn "%d" n // ...and this: type DestructureInMethod() = member tM(SingleCaseUnion n) = printfn "%d" n 

But I can’t figure out how to do this:

 type DestructureInCtor(SingleCaseUnion n) = do printfn "%d" n // type DestructureInCtor(SingleCaseUnion n) = // ---------------------------------------^ // // stdin(3,40): error FS0010: Unexpected identifier in type definition. Expected ')' or other token. 

Is my syntax incorrect or does F # not support pattern matching in constructor options?

+5
source share
1 answer

No, the language specification explicitly says no:

 primary-constr-args : attributesopt accessopt (simple-pat, ... , simplepat) simple-pat : | ident | simple-pat : type 

As already noted, secondary constructors allow parameters that are consistent with the sample, but the difference with the main designer is each of the main parameters, both a function parameter and a private field declaration.

If F # allowed pattern matching here, there would be some patterns that would violate this one-parameter relationship.

 type DestructureInCtor(SingleCaseUnion _) = // doesn't declare a private field 

or:

 type DestructureInCtor((a:int, b:int)) = // declares two private fields? 

It is possible that this might work, but I assume that the complexity of resolving pattern matching can be expanded to provide field declarations that outweigh the benefits.

+5
source

Source: https://habr.com/ru/post/1212004/


All Articles