In this article we're going to see how we can solve this problem using another flavors of Pattern-Matching.
Using active patterns you can define case names (partitions of your data) so that you can use these names in Pattern-Matching expressions. A typical example could be this one:
So let's use active pattern to resolve FizzBuzz kata. The active pattern could be something like this:
As you can see we have an active recognizer that defines four cases. Inside the recognizer we're using Pattern-Matching to select the appropriate case as we did in the original implementation of the kata. Now, we just have to use this recognizer in a Pattern-Matching function:
As you can see, we are using a Pattern-Matching function, a convenient shortcut for creating a Pattern-<atching lambda expression. We are just replacing the match...with portion of the match expression with function.
Now, if we would like to print the first 100 numbers we can do something like this:
In this case we are using a range expression to create a sequence with numbers from 1 to 100. Using the pipe forward operator we are passing this sequence to the map function of the Seq module that transforms a sequence applying a function (in this case fizzBuzz) to every element in a sequence. Finally, we iterate over the sequence to print the results.
Partial Active Patterns
Active patterns have to limitations:
- Each input must map to a named case.
- Are limited to seven named cases.
An alternative to active patterns are partial active patterns. A partial active pattern include only a single case name followed by an underscore. Let's rewrite the FizzBuzz kata using partial active patterns.
First, we have to write the active patterns we are going to use:
And after that, we are ready to use them in a Pattern-Matching expression:
Parameterized Active Patterns
It's possible to use a function that accepts more than the match value. Let's define a Parameterized partial active pattern (remember to include additional parameters before the match input argument.
And now, let's use this partial active pattern:
And that's all for today. All these samples are extracted from the excellent book The book of F#, so I can't recommend it enough if you want to learn F#.
As usual, I'm just learning F#. If you see something incorrect or you want to add an alternative solution, please leave a comment.
Author Vicenç García