通过函数调用进行模式匹配 [英] Pattern matching by function call
本文介绍了通过函数调用进行模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
F#通过模式匹配分配函数参数.这就是为什么
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)
有效:元组与(a,b)匹配,并且a和b直接在f内部可用.
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?
推荐答案
您需要额外的括号:
let f (A.X(a, b)) = a + b
这篇关于通过函数调用进行模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文