Reputation: 3949
I have a list lst
of objects of type value
where
type value = A of int | B of bool | C of string
In doing some matching on the the list, I tried to write
match lst with
| A x :: val :: tl -> ...
and got an exception saying that in the variable val
a pattern was expected. I am assuming this is because in the head of the list I matched on a value
variant, but for val
I wanted to capture all possible next entries in the list. I can think of some ways around them, like writing several cases for the several variants of val
. But since I want to do the same basic thing no matter what val
is, that seems like a very inelegant solution. Is there a better solution?
Upvotes: 0
Views: 294
Reputation: 4098
Elaborating an answer based on glennsl's comment, I assume this snippet entered into the top level is reproducing the syntax error you're hitting:
since val
is a reserved keyword, it is not legal to use it in pattern matches. The error is saying that the underlined token val
is triggering a syntax error since it is expecting something that could be part of a pattern.
The following should compile without any problems (using some random values for example):
type value = A of int | B of bool | C of string
match [A 1; B true; C "foo"] with
| A x :: v :: tl -> Some (x, v)
| _ -> None
And this is simply due to the replacement of the keyword val
with the variable v
in the pattern.
Upvotes: 3