所以我想做的是将字符串转换为 int 并对其进行一些错误捕获。我还想知道如果它失败后我会把我想让它做的事情放在哪里。
我知道如何转换,但我不确定如何捕获它以及错误后代码将跳转到哪里
我相信将它转换为 Int.fromString(x) 的方法
谢谢。
最佳答案
SML 有两种错误处理方法。一种是基于 raise
来引发错误和 handle
来捕获错误,这有点类似于 Python 或 Java 等语言中错误处理的工作方式。它是有效的,但生成的代码往往会失去一些功能 flavor 。另一种方法基于options
的概念。因为 Int.fromString
的返回类型是
string -> int option
使用基于选项的方法最有意义。
int 选项
要么是SOME n
,其中n
是整数,要么是NONE
。如果函数 Int.fromString
尝试将字符串转换为整数失败,则返回后者。调用 Int.fromString
的函数可以显式测试 NONE
并在返回值为的情况下使用 valOf
提取值SOME n
形式。或者,更习惯一点的是,您可以在 case
表达式中使用模式匹配。这是一个玩具示例:
fun squareString s =
case Int.fromString(s) of
SOME n => Int.toString (n * n) |
NONE => s ^ " isn't an integer";
此函数的类型为 string -> string
。典型输出:
- squareString "4";
val it = "16" : string
- squareString "Bob";
val it = "Bob isn't an integer" : string
请注意,以 NONE =>
开头的子句基本上是一个错误处理程序。如果您定义的函数无法处理此类错误,它可能会推卸责任。例如:
fun squareString s =
case Int.fromString(s) of
SOME n => SOME (Int.toString (n * n))|
NONE => NONE;
这有类型 string -> string option
输出现在看起来像:
- squareString "4";
val it = SOME "16" : string option
- squareString "Bob";
val it = NONE : string option
这将使调用者有责任弄清楚如何处理该选项。
关于error-handling - SML 将字符串转换为带有错误捕获的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35590313/