我有一个这样的歧视工会:
type A = |B | C of int*A
我必须像这样进行模式匹配(似乎需要括号):
match x with
| B -> printfn "B"
| C (i,a) -> printfn "%A, %A" i a
有没有办法像这样将其与 Activity 模式匹配:
match x with
| B -> printfn "B"
| C i a -> printfn "%A, %A" i a
如果不是这样,那么如何设计F#使其无法与匹配的参数匹配,而是迫使您使用元组?
编辑:这是受F#列表的启发,您可以在其中使用
h::t
而不进行任何扭曲或类似操作。源代码如下:type List<'T> =
| ([]) : 'T list
| (::) : Head: 'T * Tail: 'T list -> 'T list
最佳答案
不能将空格用作绑定(bind)模式之间的分隔符,因为联合用例和 Activity 模式均不支持此功能。按照F# spec的语法:
6.9.8评估工会案例
Case(e,…,e)
7.2.3 Active Patterns
(|CaseName|) arg ... arg inp (|CaseName|_|) arg ... arg inp
So it's necessarily one tupled argument for a union case; and n+1 arguments for the banana function, of which n arguments are parameters. Only the last argument binds to the pattern. Consider:
type X = B | C
let (|C|) a b = C (a, b)
let i = 42
match C with
| B -> printfn "B"
| C i a -> printfn "%A, %A" i a // prints 42, (42, C)
关于f# - 歧视工会中的 curry 论点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39169500/