Matching F # and the 'as' Pattern

I am learning F # and trying to implement a parser combinator, as in this tutorial ; after some copy and paste of the proposed solution, I tried to configure it myself.

Of course, there I missed something, but the compiler gives me a strange error message.

type T<'a> = | A of string | B of 'a let foo ab = match a with | A s as x -> x | B i -> match b with | A s as x -> x | B j -> B (i, j) 

The above code is a generalization of the problem I discovered: the error is notified in the last result (branch B of the innermost match):

 error FS0001: Type mismatch. Expecting a 'a but given a 'a * 'b The resulting type would be infinite when unifying ''a' and ''a * 'b' 

But if I do not use the as pattern:

 let foo ab = match a with | A s -> A s // it can also be '| A s as x -> A s' | B i -> match b with | A s -> A s | B j -> B (i, j) 

then the compiler will be happy again.

I do not understand why I need to recreate the same logical result, if it already exists.

+7
pattern-matching f #
source share
1 answer

IN

 A s as x -> x 

x is of type T<'a> , and the required return type for foo is T<('a * 'a)> . Although case A contains no values โ€‹โ€‹of 'a , it does not have a polymorphic type like forall 'a . T<'a> forall 'a . T<'a> . In the second example, you create a new instance of A , which may be of the required type.

+7
source share

All Articles