BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News F# Extends its String Interpolation Syntax to Reduce Escaping

F# Extends its String Interpolation Syntax to Reduce Escaping

F# has introduced a new syntax feature in preview to make it easier to work with interpolated strings. The main advantage of the new syntax is it allows to customize how many curly braces delimit an interpolated expression, thus reducing the need for escaping special characters.

The new syntax applies to verbatim interpolated strings, i.e. to interpolated strings using triple quotes. In such cases, F# allowed to prefix a triple-quoted string with a single $ sign, which meant { and } were used to embed F# expressions into the string.

The new syntax mimics C#'s string interpolation design, which enables using double dollar signs as a way to specify that interpolation is started by two curly braces, instead of just one.

This is an example of how you can use the new string interpolation syntax, which also shows the use the single curly brace delimiter without escaping it.

let json = $$"""
{
  "id": "Some guid",
  "name": "{{user.Name}}",
};
"""

Compare it to what the previous syntax required to type:

let json = $"""
\{
  "id": "Some guid",
  "name": "{user.Name}",
\};
"""

According to F# engineer Adam Boniecki, the new syntax is most useful to generate CSS or JSON content, where curly braces are ubiquitous and the only syntax would require lots of escaping.

You don’t have to comb through all your string literals looking for {, } or % characters to escape, you can just write (or copy-paste) them as you normally would.

The new F# syntax is flexible, allowing you to start interpolated strings with as many {} signs as required, matching the number of $ signs. For example:

let template = $$$"""
<div class="{{{classAttr}}}">
  <p>{{title}}</p>
  <div><img alt="item" src="{{itemImageUrl}}"></div>
  <button type="button" class="add" (click)="add(item)">Add</button>
</div>
"""

While, as mentioned, the design of this new feature follows C#'s string interpolation, there are a number of significant differences motivated by the need to be backward compatible and not break any existing code. For example, multi-line raw string literals in C# must start with a new line, which is automatically ignored; in F#, you can add a new line, but it will not be ignored. Additionally, in C# you can start a raw string literal with any number of "s, not just three, whereas in F# you are required to use just three.

As a last note, keep in mind this is a preview feature, so you are expected to enable it using the --langversion:preview argument to dotnet fsi, or putting it in your .fsproj file under <OtherFlags>.

About the Author

Rate this Article

Adoption
Style

BT