F# type test pattern matching: decomposing tuple objects

半腔热情 提交于 2021-02-10 14:19:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!