How to partially apply an active pattern

148 views Asked by At

The Fsharpx.Extras NuGet package exposes an active pattern for regular expression matching, qualified as Fsharpx.Text.Regex.Match.

The first parameter is a RegexOptions value from the BCL.

Rather than having to write:

let someFunc =
    | Match RegexOptions.None "...pattern 1..." matches -> ...
    | Match RegexOptions.None "...pattern 2..." matches -> ...
    | Match RegexOptions.None "...pattern 3..." matches -> ...
    ...

I was hoping it would be possible to instead have (using a revised Match' active pattern):

let someFunc =
    | Match' "...pattern 1..." matches -> ...
    | Match' "...pattern 2..." matches -> ...
    | Match' "...pattern 3..." matches -> ...
    ...

One possible definition of Match' I came up with was:

let (|Match'|_|) pattern =
    function
    | Match RegexOptions.None pattern matches -> Some matches
    | _ -> None

...which works fine. However, I couldn't help wonder if there was another approach similar to a partially applied function such as:

let (|Match'|_|) =
    Match RegexOptions.None

Frustratingly, this complains about Type has no accessible object constructors..

Is something similar to the latter (alebit failing) approach possible?

1

There are 1 answers

1
Jim Foye On BEST ANSWER

Open the Regex module, then change your last example to

let (|Match|_|) = (|Match|_|) RegexOptions.None

In fact, if you look at the source code, you'll see an example of this in the Compiled module.

https://github.com/fsprojects/FSharpx.Extras/blob/master/src/FSharpx.Extras/Regex.fs

Related Questions in F#