Pattern matching by function call

邮差的信 提交于 2019-12-11 03:43:41

问题


F# assigns function arguments via pattern matching. This is why

// ok: pattern matching of tuples upon function call
let g (a,b) = a + b
g (7,4)

works: The tuple is matched with (a,b) and a and b are available directly inside f.

Doing the same with discriminated unions would be equally beneficial, but I cannot get it to done:

// error: same with discriminated unions
type A = 
    | X of int * int
    | Y of string

let f A.X(a, b) = a + b // Error: Successive patterns 
                        // should be separated by spaces or tupled

// EDIT, integrating the answer:
let f (A.X(a, b)) = a + b // correct

f (A.X(7, 4))

Is pattern matching as part of the function call limited to tuples? Is there a way to do it with discriminated unions?


回答1:


You need extra parens:

let f (A.X(a, b)) = a + b


来源:https://stackoverflow.com/questions/21387954/pattern-matching-by-function-call

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