Strings and `\`, how to escape characters in the different types of string literals

Hi!

I’m trying to write in code a string that when printed will output \a -> a. Escaping the backslashes is proving challenging depending on the type of string literal I’m using, for example:

Playground link

let f = "\\a -> a" // Fine, as expected

// Doesn't compile:
// [E] Line 6, column 9:
// Offset: 1, Invalid escape code: a
let f' = `\\a -> a`

let f'' = `\\\a -> a` // Triple backslash makes it work for some reason?

Is there a reason for this or a bug? I’d appreciate any help understanding how escaping works in the different string literals.

I try to default to backticks for literals in code due to the unicode support, but I’m not sure I understand the escaping rules now.

Thanks!

1 Like

`` does not do the escape based on my understanding. This seems to be a bug, would you file an issue on rescript-lang/syntax repo

Not exactly, the output JS is "\\a -> a".

If you see the JS output, both f and f'' have the same output, which is what’s needed, an escaped \ is \\ in JS so that when console.logged it outputs \a -> a.

Sure thing!

1 Like

In case someone in the future needs the link: Escaping a backslash in backtick strings doesn't work well · Issue #429 · rescript-lang/syntax · GitHub

1 Like