Book Image

Testing with F#

By : Mikael Lundin
Book Image

Testing with F#

By: Mikael Lundin

Overview of this book

Table of Contents (17 chapters)
Testing with F#
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Writing testable code


In the previous section we have been looking at basic functional structures that helps us write better programs. Now we're ready to move on to higher level constructs that let us organize our code functionally on a more abstract way.

Active patterns

Pattern matching is one of the killer features of F# that makes it a more attractive language than C# or Visual Basic. It could have been just a nice language feature for the built-in .NET types, but actually it is highly customizable and you can define your own patterns.

Here is how you can define your own active pattern:

// active pattern for sequences
let (|Empty|NotEmpty|) sequence =
    if Seq.isEmpty sequence then Empty
    else NotEmpty sequence

This enables us to use the pattern directly in a match expression:

// example on usage of active pattern
// join ["1"; "2"; "3"] -> "123"
let rec join (s : seq<string>) = 
    match s with
    | Empty -> ""
    | NotEmpty s -> (Seq.head s) + join (Seq.skip 1 s)

The...