4

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?

Magg G.
  • 229
  • 3
  • 10
  • 4
    When constructing values you don't need `of`: `"abcd" -> Some (bar2 a)` – Lee Jun 10 '15 at 12:05
  • @Lee Oh wow, that was a really small mistake. Thank you! You should submit that as an answer and I will accept it – Magg G. Jun 10 '15 at 12:07

1 Answers1

6

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
Lee
  • 142,018
  • 20
  • 234
  • 287