StringBuffer 1.0.2

Edit this page

StringBuffer


What is StringBuffer?

StringBuffer is an F# computation expression for being able to easily write formatted text.

It is built with the goal of being able to easily write code within an F# program.

Why use StringBuffer?

As part of working on other projects I found myself needing to generate F# code within a program.

This was particularly problematic considering F#, like many languages, is whitespace sensitive, using indentation to declare scopes.

I found myself needing a way to create code with correct indentation while still being able to break apart large chunks of generated code into smaller sections that could be built separately and then put together to create the final file.


Installing StringBuffer

Simply add it from nuget, paket, however you source your packages. The module automatically opens and will be available throughout your project.

Find the latest version at

The module provides two computation expressions:

Samples

Basic build

let result = stringBuffer {
    "My first line"
    "My second line"
    sprintf "This line has a number in it: %i" 3
}

Output

My first line
My second line
This line has a number in it: 3

Using variables and loops

let firstLine = "Line 1"
let moreLines = [2 .. 5]

let result = stringBuffer {
    firstLine
    moreLines |> Seq.map(fun i -> sprintf "Line %d" i)
}

Output

Line 1
Line 2
Line 3
Line 4
Line 5

Use multiple lines, even other instances of stringBuffer

let firstTwoLines = seq {
    "Line 1"
    "Line 2"
}

let thirdLine = "Line 3"

let result = stringBuffer {
    firstTwoLines
    thirdLine
    "Line 4"

    stringBuffer {
        "Line 5"
    }

}

Output

Line 1
Line 2
Line 3
Line 4
Line 5

Indenting

let result = stringBuffer {
    "let square x ="
    indent {
        "x * x"
    }
}

Output

let square x =
    x * x
val result: obj
val sprintf: format: Printf.StringFormat<'T> -> 'T
module Seq from Microsoft.FSharp.Collections
val map: mapping: ('T -> 'U) -> source: seq<'T> -> seq<'U>
Multiple items
val seq: sequence: seq<'T> -> seq<'T>

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>