Template strings in F#?

Viewed 1793

I'm new to F#, and want to know if there is anything in F# similar to template strings in Python. So I can simply do something like:

    >>> d = dict(who='tim', what='car')
    >>> Template('$who likes $what').substitute(d)
    'tim likes car'
4 Answers

New in F# 5 is string interpolation:

let firstName = "John" 
let lastName = "Doe" 

let newString = $"First Name: {firstName} Last Name: {lastName}" 

Or without local bindings (note the triple quotes):

let newString = $"""First Name: {"John"} Last Name: {"Doe"}"""

Older versions of F# should use sprintf:

let newString = sprintf "First Name: %s Last Name: %s" "John" "Doe"

If you have a dynamic list of substitutions, you can achieve what Template() does with a simple fold:

let substitutions = [("who", "tim"); ("what", "car")]
let template = "{who} likes {what}"
let replace (str : string) (key, value) = str.Replace(sprintf "{%s}" key, value)  

List.fold replace template substitutions
Related