More complex pattern matching in F#

Pattern matching branches in F# can be more advanced using the when keyword. Consider the following list matching function:

let listMatcher (l:list<'a>) =
    match l with
        | _ when l.IsEmpty -> "This is an empty list"
        | _ when l.Length > 10 -> "This is a large list"
        | _ when l.Length < 10 -> "This is a small list"
        | _ -> l |> (sprintf "%A") |> String.concat ","

We accept lists of any type, hence the type declaration of generic list. We then go on and test the length of the list in 4 branches. The underscore means that we won’t use the matched value, i.e. we don’t really need pattern matching. This is a wildcard pattern matching as noted on this page.

The real test comes after the when keyword. If the list is empty then we return “This is an empty list”. We then have 2 branches to see if the list length is less than or greater than 10. The fourth branch has no “when” keyword which works as the catch-all branch. In our case it will catch all lists with exactly 10 elements and return a concatenated string from its elements. The last branch is similar to a “default” branch in a C# switch block.

Here’s how we can use the above pattern matching function:

let myFirstList = []; 
let myRangeList = [2..2..20] 
let myLargeList = [0..100]     
let mySmallList = [0..5] 
printfn "Result: %s" (myFirstList |> listMatcher)         
printfn "Result: %s" (myRangeList |> listMatcher)     
printfn "Result: %s" (myLargeList |> listMatcher)
printfn "Result: %s" (mySmallList |> listMatcher)

Here’s the output:

Result: This is an empty list
Result: 2,4,6,8,10,12,14,16,18,20
Result: This is a large list
Result: This is a small list

View all F# related articles here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: