MiloDC
MiloDC

Reputation: 2415

F# type test pattern matching: decomposing tuple objects

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?

Upvotes: 1

Views: 324

Answers (1)

Gus
Gus

Reputation: 26184

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

Upvotes: 2

Related Questions