United Kingdom: +44 (0)208 088 8978

String Interpolation in F#

Coming up to F# 5, string interpolation was one of the most requested features – and it's just been released with F# 5 Preview 1.

String Interpolation in F#

String interpolation was a highly requested feature on the way to F# 5 Preview 1. The idea, essentially, is to allow a string literal containing one or more placeholders to be filled in later. To do this, we write code in "holes" inside of a string literal using the dolar sign and curly brackets.

A Simple Case

Let's compare this approach to using the sprintf function. Before string interpolation, to insert the value of an integer into a string we would do this:

let x = 12
sprintf "The number is %i." x

// Result: "The number is 12."

After the string interpolation update, we can place x directly inside the string literal like so:

let x = 12
$"The number is {x}"

// Result: "The number is 12."

More Complex Interpolations

Though this might not appear to be huge, consider having this anonymous record in your code.

let person = 
    {| Name = "John"
       Surname = "Doe"
       Age = 32
       Country = "The United Kingdom" |}

And you want to write a greetings message that includes all of the person's details. With the old approach it would look like the following.

sprintf 
    "Hi! My name is %s %s. I'm %i years old and I'm from %s!" 
    person.Name 
    (person.Surname.ToUpper())
    person.Age
    person.Country

// Result: Hi! My name is John DOE. I'm 32 years old and I'm from The United Kingdom!"

Compare the code above to this interpolated string:

$"Hi! My name is {person.Name} {person.Surname.ToUpper()}. I'm {person.Age} years old and I'm from {person.Country}!"

// Result: Hi! My name is John DOE. I'm 32 years old and I'm from The United Kingdom!

Typed Interpolations

Similar to the sprintf function, interpolated strings will also allow for typed interpolations to enforce that an expression inside of an interpolated context is of a certain type. See:

$"Hi! My name is %s{person.Name} %s{person.Surname}. I'm %i{person.Age} years old and I'm from %s{person.Country}!"

// Result: Hi! My name is John Doe. I'm 32 years old and I'm from The United Kingdom!

Closing Thoughts

What do you think? Is this feature one of your favourites or not even close? I find the ability to see the variable names exactly where their values will be inserted in the string way more intuitive and readable than having them listed one after the other at the end.

Thank you for reading this short blog post on string interpolation. To find out more about the features included in F# 5 Preview 1, check out this blogpost from Phillip Carter at Microsoft.