0

I'm writing an SML program and I'm trying to convert a string that has escape sequences into a string that does not have escape sequences.

I've tried this, but it doesn't seem to work (prints just "Hello ")

fun test x  =
let val esc = "Hello \\  Bob \n Newman"
    val fixed = String.fromString esc
in
    print (valOf(fixed))
end

I think I might have to use the String.scan function however, I don't exactly understand how it works.

The function signature is

scan       : (char, 'a) StringCvt.reader
                   -> (string, 'a) StringCvt.reader

So I have a few questions:

1) Can you expalin what exactly this scan signature is saying...What arguments does the function take and what does it return

2) Is this the function that I should be using?

3) Can you give me any guidance on using this function. Thanks

EDIT: Ok, so the above example I simplified, but I may have simplified it too much...Here's exactly what I'm doing. I'm have a global string called str and and input stream of chars/strings...As I read the input stream, I concatenate str with the character that I just read. After I have read all of the characters, I want to return str but with all of the escape sequences converted.

4

2 回答 2

1

我刚刚解雇了 PolyML 并尝试了以下方法:

Poly/ML 5.5.0 Release
> val a = "Hello \\ Bob \n Newman";
val a = "Hello \\ Bob \n Newman": string
> print a;
Hello \ Bob 
 Newmanval it = (): unit
> print (String.toString a);
Hello \\ Bob \n Newmanval it = (): unit
>

换句话说,默认情况下,转义序列已经被解释为它们所代表的字符,并且您必须使用String.toString“取消转义”特殊字符(获取包含原始转义序列的字符串)。或者,更好的是,您可以使用转义序列本身对转义序列进行编码,如 Andreas 所示。

于 2013-02-01T23:32:11.477 回答
1

您似乎对示例中发生的转义量感到困惑。

当你写

val s1 = "Hello \n world!"

那么转义已经被 SML 解析器解释了,s1它本身在运行时不会包含任何内容。您可以按原样打印字符串。

在运行时实际包含转义的字符串例如是

val s2 = "Hello \\n world!"

因为这里 SML 解析器解释\\为(单个)斜杠。然后,您可以s2在运行时使用进行转换String.fromString,生成与 . 相同的字符串s1

回到你的例子,esc表示运行时字符串

Hello \  Bob 
 Newman

斜线后跟一个空格。这不是一个有效的转义序列,因此String.fromString只会将字符串转换为那个“解析”错误(这是fromStringSML 中所有函数的语义——如果你直接使用底层scan函数,你也会得到其余的字符串)。

于 2013-02-02T11:01:24.107 回答