与歧视联盟的主动模式匹配

时间:2015-06-10 12:01:37

标签: f# pattern-matching discriminated-union active-pattern

有没有办法使用以下形式的区别联合与活动模式匹配?我找不到任何例子。

这就是我要做的事情:

type c = a | b

type foo =
  | bar1
  | bar2 of c

//allowed
let (|MatchFoo1|_|) aString =
  match aString with
  | "abcd" -> Some bar1
  | _ -> None

//not allowed
let (|MatchFoo2|_|) aString =
  match aString with
  | "abcd" -> Some (bar2 of a)
  | _ -> None

为什么“Some”不能以第二种方式使用?还有另一种方法可以达到同样的目的吗?

1 个答案:

答案 0 :(得分:6)

在声明类型时,您只需要使用of,因此您可以使用bar2构造函数构造值,如:

bar2 a

如果将其更改为:

,则第二个功能应该有效
let (|MatchFoo2|_|) aString =
  match aString with
  | "abcd" -> Some (bar2 a)
  | _ -> None