我想把一个字符串转换成整数,并对其进行错误捕获。如果发生错误,我也想知道在哪里放置处理错误的代码。
我知道如何进行转换,但不确定如何捕获错误和错误后代码会跳到哪里。
我相信转换的方法是 Int.fromString(x)。
谢谢。
我想把一个字符串转换成整数,并对其进行错误捕获。如果发生错误,我也想知道在哪里放置处理错误的代码。
我知道如何进行转换,但不确定如何捕获错误和错误后代码会跳到哪里。
我相信转换的方法是 Int.fromString(x)。
谢谢。
raise
抛出错误和 handle
捕捉错误,与Python或Java等语言中的错误处理方式有些相似。这种方法是有效的,但导致的代码往往会失去一些功能性。另一种方法是基于“选项”的概念。由于 Int.fromString
的返回类型是string -> int option
使用基于选项的方法是最有意义的。
int option
要么是 SOME n
,其中 n
是整数,要么就是 NONE
。函数 Int.fromString
如果在尝试将字符串转换为整数时失败,则返回后者(NONE
)。调用 Int.fromString
的函数可以显式地测试是否为 NONE
,并在返回的值是 SOME n
形式时使用 valOf
提取值。或者,更符合惯例的做法是,在 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
fun squareString s = Int.fromString s >>= (fn i => SOME (i*i))
>>=
运算符为:infix 3 >>=
fun NONE >>= _ = NONE
| (SOME a) >>= f = f a
o
运算符)以及大量嵌套的情况处理语句。fun inputSqrt s =
case TextIO.inputLine TextIO.stdIn of
NONE => NONE
| SOME s => case Real.fromString s of
NONE => NONE
| SOME x => SOME (Math.sqrt x) handle Domain => NONE
fun safeSqrt x = SOME (Math.sqrt x) handle Domain => NONE
fun inputSqrt () =
TextIO.inputLine TextIO.stdIn >>=
(fn s => Real.fromString s >>=
(fn x => safeSqrt x))
fun inputSqrt () = TextIO.inputLine TextIO.stdIn >>= Real.fromString >>= safeSqrt
datatype ('a, 'b) either = Left of 'a | Right of 'b
infix 3 >>=
fun (Left msg) >>= _ = Left msg
| (Right a) >>= f = f a
fun try (SOME x) _ = Right x
| try NONE msg = Left msg
fun inputLine () =
try (TextIO.inputLine TextIO.stdIn) "Could not read from stdIn."
fun realFromString s =
try (Real.fromString s) "Could not derive real from string."
fun safeSqrt x =
try (SOME (Math.sqrt x) handle Domain => NONE) "Square root of negative number"
fun inputSqrt () =
inputLine () >>= realFromString >>= safeSqrt
- inputSqrt ();
9
> val it = Right 3.0 : (string, real) either
- inputSqrt ();
~42
> val it = Left "Square root of negative number" : (string, real) either
- inputSqrt ();
Hello
> val it = Left "Could not derive real from string." : (string, real) either
- (TextIO.closeIn TextIO.stdIn; inputSqrt ());
> val it = Left "Could not read from stdIn." : (string, real) either