ML 中的截断第 2 部分
Truncation in ML Part 2
我即将在 ML 中截断字符串,但收到有关未处理空列表的错误。这是我的代码和错误:
fun getAllButLast([x]) = nil
| getAllButLast(x::xs) = x::getAllButLast(xs);
fun truncate(myString, 1) = str(hd(explode(myString)))
| truncate(myString, limit) =
let
val x::xs = explode(myString);
in
str(x) ^ truncate(implode(getAllButLast(xs)), limit - 1)
end;
我加载文件并调用 truncate("heythere", 5),它应该给我 "heyth"。相反,我收到此错误:
uncaught exception Empty
raised at: smlnj/init/pervasive.sml:209.19-209.24
这非常令人惊讶,因为只要我输入一个 $\ge$ 1 的限制数字(第二个参数),字符串(或代表该字符串的字符列表)就永远不会为空。
知道发生了什么事吗?
谢谢,
克莱曼
您在每个递归步骤中删除了两个字符:第一个 (x
) 和最后一个。所以字符串的长度在 limit
达到 1.
之前很久就达到了 0
FWIW,这里有一个更简单的解决方案:
fun truncate(s, n) = implode(List.take(explode s, n))
我即将在 ML 中截断字符串,但收到有关未处理空列表的错误。这是我的代码和错误:
fun getAllButLast([x]) = nil
| getAllButLast(x::xs) = x::getAllButLast(xs);
fun truncate(myString, 1) = str(hd(explode(myString)))
| truncate(myString, limit) =
let
val x::xs = explode(myString);
in
str(x) ^ truncate(implode(getAllButLast(xs)), limit - 1)
end;
我加载文件并调用 truncate("heythere", 5),它应该给我 "heyth"。相反,我收到此错误:
uncaught exception Empty
raised at: smlnj/init/pervasive.sml:209.19-209.24
这非常令人惊讶,因为只要我输入一个 $\ge$ 1 的限制数字(第二个参数),字符串(或代表该字符串的字符列表)就永远不会为空。
知道发生了什么事吗?
谢谢, 克莱曼
您在每个递归步骤中删除了两个字符:第一个 (x
) 和最后一个。所以字符串的长度在 limit
达到 1.
FWIW,这里有一个更简单的解决方案:
fun truncate(s, n) = implode(List.take(explode s, n))