5

Is there a way to nest calls to active patterns?

Something like this:

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

Or is the match followed by another match the preferred way to go?

James Moore
  • 8,636
  • 5
  • 71
  • 90

1 Answers1

12

It works. You just have the patterns backwards.

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
gradbot
  • 13,732
  • 5
  • 36
  • 69
  • @AlexeyRomanov Well, the ability to nest patterns in their main benefit over other forms of dispatch, e.g. virtual methods. – J D Mar 11 '13 at 21:06