Monthly Archives: March 2017

Pattern Matching with Constants

Pattern matching is a staple of any functional programming language. F# has a decent pattern matching system with 16 matching patterns out of the box. You also have the ability to extend the pattern matches by using Active Patterns. Let’s start with some common pattern matches for F#.

The basic syntax for pattern matching in F# is a match with expression. The with is then followed by a vertical bar and a pattern.

match item_to_be_matched with
| pattern -> result

This is a single case pattern match. It’s not used much at all. Generally pattern matches have multiple cases. Each pattern is separated by a vertical bar. You can think of the vertical bar as being “OR”.

match item_to_be_matched with
| pattern1 -> result1
| pattern2 -> result2
.
.
.
| patternN -> resultN

Constant Pattern

Using a constant pattern is very similar to a switch statement in C#. Any type that can be defined as a constant can be used in this type of pattern.

match number with
| 0 -> "Zero"
| 1 -> "One"
| 2 -> "Two"
match role with
| "administrator" -> Administrators
| "manger"        -> Managers
| "user"          -> Users

Exhaustive vs Incomplete Patterns

A pattern match is considered exhaustive when it accounts for every possible pattern. We don’t always have to use exhaustive patterns, however we do run the risk of receiving an exception if no match is found. If you are using an editor like Visual Studio or Visual Studio Code (with Ionide-Fsharp) you will get highlighting indicating a pattern may not be accounting for every possibility. It’s preferable to use exhaustive patterns to eliminate the possibility of a match failure exception.

Visual Studio Code with Ionide-Fsharp indicating an incomplete pattern.
VSCode with Ionide-FSharp - Incomplete Match

Wildcard Pattern

The wildcard pattern is used as a catch all pattern. This is denoted by an underscore or a generic label in the pattern. Use of an underscore informs the next developer the value is of no importance. The wildcard pattern is very much like the default clause of a switch statement in C#. This will take any incomplete pattern and make it exhaustive. We can make the isZero function exhaustive by adding the wildcard pattern.

let isZero number = match number with
                    | 0 -> true
                    | _ -> false
let greeting name = match name with
                    | "hal" -> printfn "I'm afraid I can't do that Dave"
                    | _     -> printfn "Hello %s" name

You do have to be careful when using the wildcard. If a business requirement changes and you forget to add the new pattern, the wildcard will happily swallow the match thus leaving you with some unintended results.

Summary

Pattern matching with constants is very similar to the C# switch construct. This is where the similarities end until C# 7. As I mentioned at the beginning of this post, F# has 16 different patterns. We’ll be getting into more of those patterns in future posts. Here is a FizzBuzz implementation using the constant pattern match with Tuple deconstruction. Exciting things are on the way.

let printFizzBuzz number = match (number % 3, number % 5) with
                           | (0, 0) -> printfn "FizzBuzz"
                           | (0, _) -> printfn "Fizz"
                           | (_, 0) -> printfn "Buzz"
                           | _      -> printfn "%d" number

F# Prototyping with Visual Studio Code

I’ve been using Visual Studio Code (VSCode) for the majority of my F# development since December 2016. I have to admit it has become my prototyping tool of choice. Visual Studio Code is a nice lightweight IDE, if you can call it an IDE. It’s more of a text editor with a great set of extensions. VSCode loads very quickly which makes it excellent for testing out those single shot ideas. VSCode is a cross platform editor which contributes to its ease of use. You get relatively the same feel on Windows, Mac OSx, or linux. Visual Studio Code, with a few extensions, has become my main editor for prototyping in F#.

If you haven’t looked at VSCode before, you can get it at https://code.visualstudio.com/.

The very first thing I do after installing VSCode is getting the Ionide-fsharp extension. You can install the extension by going to View -> Extensions in the menu. In the extensions window, enter ionide-fsharp in the search box. The extension should show in the results window with an install button.

Ionide-Fsharp will give you access to F# Interactive (F#’s REPL) from within VSCode. You also get a wide range of benefits such as syntax highlighting, codelens for function types, hover tooltips, and more. When it comes to prototyping though, having immediate feedback of a REPL is the best tool one could have.

I add some custom keybindings in VSCode for interacting with the REPL. My preferred shortcuts are as follows:

  • Ctrl+i – Starts / restarts the REPL
  • Ctrl+’ – Sends the current line from the editor to the REPL for evaluation
  • Ctrl+; – Sends the selection of code from the editor to the REPL

You can modify the keybindings by going into (Mac) Code -> Preferences -> Keyboard Shortcuts or (Windows) File -> Preferences -> Keyboard Shortcuts and adding the code snippet below:

    { "key": "ctrl+;",                "command": "fsi.SendSelection",
                                     "when": "editorTextFocus" },
    { "key": "ctrl+'",                "command": "fsi.SendLine",
                                     "when": "editorTextFocus" },
    { "key": "ctrl+i",                "command": "fsi.Start",
                                     "when": "editorTextFocus" }

Visual Studio Code and Ionide-Fsharp have truly changed how I prototype ideas. I can load the editor, start the REPL, and begin testing my ideas in mere seconds. This makes VSCode enjoyable and efficient for F# prototyping.