2010-01-04 82 views
5

有没有将调用嵌套到活动模式的方法?有没有办法将调用嵌套到F#活动模式?

事情是这样的:

type Fnord = 
| Foo of int 

let (|IsThree|IsNotThree|) x = 
    match x with 
    | x when x = 3 -> IsThree 
    | _ -> IsNotThree 

let q n = 
    match n with 
    | Foo x -> 
    match x with 
    | IsThree -> true 
    | IsNotThree -> false 
    // Is there a more ideomatic way to write the previous 
    // 5 lines? Something like: 
// match n with 
// | IsThree(Foo x) -> true 
// | IsNotThree(Foo x) -> false 

let r = q (Foo 3) // want this to be false 
let s = q (Foo 4) // want this to be true 

或者是跟其他比赛对手的首选方式去?

+3

+1为Fnord。 – bmargulies 2010-01-04 01:14:43

+0

该死的语言是不可读的。认真 - Python能做什么? – 2010-01-04 01:24:14

+8

@lpthnc:模式匹配? – Chuck 2010-01-04 01:35:38

回答

12

它的工作原理。你只是把图案倒过来。

type Fnord = 
| Foo of int 

let (|IsThree|IsNotThree|) x = 
    match x with 
    | x when x = 3 -> IsThree 
    | _ -> IsNotThree 

let q n = 
    match n with 
    | Foo (IsThree x) -> true 
    | Foo (IsNotThree x) -> false 

let r = q (Foo 3) // want this to be true 
let s = q (Foo 4) // want this to be false 
+0

其实我有点惊讶这个作品。 – 2010-01-04 15:42:57

+0

@AlexeyRomanov那么,在其他形式的调度中嵌套模式的主要好处的能力,例如,虚拟方法。 – 2013-03-11 21:06:19

相关问题