Search code examples
escapingsmlsmlnj

Char.toString without special handling of " and \


I am trying to convert characters into strings like so:

Char.toString(#"x")

For most characters this works, however for " and \, an extra \ is added before it:

- Char.toString(#"\"");
val it = "\\\"" : string

This is undesirable behavior for me. I want the above code snippet to return val it = "\"" : string. Is there any built-in function in SML that can do this?


Solution

  • From the documentation of Char.toString:

    returns a printable string representation of the character, using, if necessary, SML escape sequences. Printable characters, except for #"\" and #"\"", are left unchanged. Backslash #"\" becomes "\\"; double quote #"\"" becomes "\\"". [...]

    To convert a character to a length-one string containing the character, use the function String.str.

    And from the documentation of String.str:

    str c is the string of size one containing the character c.

    So str #"\"" will do exactly what you want.