Fsharp: Dollar Sign String (Template, Interpolated)

By Xah Lee. Date: .

Dollar Sign String (Template String)

this lets you embed variable or expression inside string.

syntax:

and

the number of dollar sign correspond to the number of curly brackets need to be interpreted as embedded expression.

To include a literal curly brackets {}, use it on triple quoted string, and use double bracket {{}}. In general, use one more level of bracket than the number of dollar sign.

let tt = 3
let xx = $"have {tt} thing"
printfn "%s" xx
// have 3 thing
let tt = 3
let xx = $"have {tt} {{tt}} thing"
printfn "%s" xx
// have 3 {tt} thing

// there is only one dollar sign.
// so {tt} is interpreted
// so {{tt}} becomes literal {tt}
let xx = 3

let aa = $"""have {xx} thing"""
printfn "%s" aa
// have 3 thing

// double dollar in front of triple quote
let bb = $$"""have {{xx}} thing"""
printfn "%s" bb
// have 3 thing
let xx = 3

// include a literal curly brackets, use extra curly brackets
let aa = $"""have {{xx}} thing"""
printfn "%s" aa
// have {xx} thing
let xx = 3

// 2 dollar sign
let aa = $$"""have {xx} {{xx}} {{{xx}}} {} thing"""
printfn "%s" aa
// have {xx} 3 {3} {} thing

// those with 2 nested curly brackets are interpreted.
// and cannot be empty.
// {{}} is error
// {{{}}} is also error

Fsharp, String