问题
Just curious why I can't do this:
let myFn (data : obj) =
match data with
| :? (string * string) as (s1, s2) -> sprintf "(%s, %s)" s1 s2 |> Some
| :? (string * string * int) as (s1, s2, i) -> sprintf "(%s, %s, %d)" s1 s2 i |> Some
| _ -> None
How come?
回答1:
See F# spec, section 7.3 "As patterns"
An as pattern is of the form pat as ident
Which means you need to use an identifier after as
:
let myFn (data : obj) =
match data with
| :? (string * string) as s1s2 -> let (s1, s2) = s1s2 in sprintf "(%s, %s)" s1 s2 |> Some
| :? (string * string * int) as s1s2i -> let (s1, s2, i) = s1s2i in sprintf "(%s, %s, %i)" s1 s2 i |> Some
| _ -> None
来源:https://stackoverflow.com/questions/64747418/f-type-test-pattern-matching-decomposing-tuple-objects