Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the main point of Active Patterns?

Tags:

f#

When we pattern match on a value using Active Patterns, there is a "convert" function implicitly called. So instead of writing:

match value with
| Tag1 -> ...
| Tag2 -> ...

I can explicitly write:

match convert value with
| Tag1 -> ...
| Tag2 -> ...

This way, I don't have to use Active Patterns here. Of course, I have to explicitly call the convert function, and have to explicitly declare a union type. But those are minor things to me.

So what is the main point of Active Patterns?

like image 773
Nghia Bui Avatar asked Jun 11 '19 03:06

Nghia Bui


1 Answers

The primary power of pattern matching is not the funny syntax. The primary power of patterns is that they can be nested.

Take a look at this:

match value with
| Foo (Bar, Baz [First 42; Second "hello!"]) -> "It's a thing"
| Qux [42; 42; 42] -> "Triple fourty-two"
| _ -> "No idea"

Assuming all capitalized words are active patterns, let's try to rewrite the first pattern in terms of calling convert explicitly:

match convertFoo value with
| Foo (x, y) -> 
    match convertBar x, convertBaz y with
    | (Bar, Baz [z1; z2]) ->
        match convertFirst z1, convertSecond z2 with
        | First 42, Second "hello!" -> "It's a thing"

Too long and convoluted? But wait, we didn't even get to write all the non-matching branches!

match convertFoo value with
| Foo (x, y) -> 
    match convertBar x, convertBaz y with
    | (Bar, Baz [z1; z2]) ->
        match convertFirst z1, convertSecond z2 with
        | First 42, Second "hello!" -> "It's a thing"
        | _ -> "No idea"
    | _ -> "No idea"
| Qux [42; 42; 42] -> "Triple fourty-two"
| _ -> "No idea"

See how the "No idea" branch is triplicated? Isn't copy&paste wonderful? :-)


Incidentally, this is why C#'s feeble attempt at what they have the audacity to call "pattern matching" isn't really pattern matching: it can't be nested, and therefore, as you very astutely observe, it is no better than just calling classifier functions.

like image 82
Fyodor Soikin Avatar answered Oct 21 '22 04:10

Fyodor Soikin