Search code examples
stringf#double-quotes

Why F# string can't end with double quote in the triple-quoted?


I'm a C# developer who try to learn F#.

As far as I know, F# 2.0 had two kind of syntaxes for strings: normal strings, and verbatim strings (like C#). With F# 3.0 version there is a feature called tripled-quoted strings.

As far as I see, with this string format, every thing between """ is a verbatim string literal. And there is no need to escape escapse sequence characters like double quotes.

For example all these are valid strings;

let a = """ This is a valid "string" """
let b = """ This is a valid \string """
let c = """ This is a valid 'string """

But there is a rule with it;

Quotes in the triple-quoted string cannot end with a double-quote (“), but it can begin with one.

So this is a legal string;

let s = """"This is a valid string"""

but this is not;

let s = """This is a valid string""""

Why is that? I looked at Strings (F#) on MSDN page, F# 3.0 Language Spec $3.5 Strings and Characters part and More About F# 3.0 Language Features but I couldn't find any information about why it's legal to use in the begining of string but not at the end.

Can you enlighten me?


Solution

  • The answer is simple: the triple-quoted string ends as soon as the compiler sees three quotes. So """a"""" is a string constisting of the character a, followed by an extra ", which starts a new string.

    If you want to write obfuscated code, you might do something like:

    f"""a""""b"
    

    To call the function f with two string "a" and "b".