开发者

Is there a way to nest calls to F# active patterns?

开发者 https://www.devze.com 2022-12-15 03:53 出处:网络
Is there a way to nest calls to active patterns? Something like this: type Fnord = Foo of int let (|IsThree|IsNotThree|) x =

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 -&开发者_StackOverflow社区gt; 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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号