2010-01-04 10 views
5

¿Hay alguna manera de anidar llamadas a patrones activos?¿Hay alguna forma de anidar llamadas a patrones activos F #?

Algo como esto:

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 

O es el partido seguido por otro partido de la manera preferida para ir?

+3

+1 for the Fnord. – bmargulies

+0

El maldito lenguaje no se puede leer. En serio, ¿qué puede hacer que Python no pueda? –

+8

@lpthnc: ¿Coincidencia de patrón? – Chuck

Respuesta

12

Funciona. Solo tienes los patrones hacia atrás.

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

Estoy un poco sorprendido de que esto funcione, en realidad. –

+0

@AlexeyRomanov Bueno, la capacidad de anidar patrones en su beneficio principal frente a otras formas de envío, p. métodos virtuales. –

Cuestiones relacionadas