4
votes

Is there any way to use a discriminated union of the following form with active pattern matching? I haven't been able to find any examples.

This is what I'm trying to do:

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

Why can "Some" not be used in the second way? Is there another way to achieve the same thing?

1
When constructing values you don't need of: "abcd" -> Some (bar2 a)Lee
@Lee Oh wow, that was a really small mistake. Thank you! You should submit that as an answer and I will accept itMagg G.

1 Answers

6
votes

You only need to use of when declaring the type, so you can just construct values with the bar2 constructor like:

bar2 a

Your second function should work if you change it to:

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