2010-01-04 76 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

相關問題