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

Immutability


The default behavior of F# when using the let keyword is an immutable value. The difference between this and a variable is that the value is not possible to change. With this, there are the following benefits:

  • It encourages a more declarative coding style

  • It discourages side effects

  • It enables parallel computation

The following is an example implementation of the String.Join function using a mutable state:

// F# implementation of String.Join
let join (separator : string) list = 
    // create a mutable state
    let mutable result = new System.Text.StringBuilder()
    let mutable hasValues = false
        
    // iterate over the incoming list
    for s in list do
        hasValues <- true
        result
            .Append(s.ToString())
            .Append(separator)
            |> ignore
            
    // if list hasValues remove last separator
    if hasValues then
        result.Remove(result.Length - separator.Length, separator.Length) |> ignore

    // get result...