我有以下代码:
- exception Negative of string;
> exn Negative = fn : string -> exn
- local fun fact 0 =1
| fact n = n* fact(n-1)
in
fun factorial n=
if n >= 0 then fact n
else
raise Negative "Insert a positive number!!!"
handle Negative msg => 0
end;有什么问题吗??我知道错误:
! Toplevel input:
! handle Negative msg => 0
! ^
! Type clash: expression of type
! int
! cannot have type
! exn我怎么才能修好它?如果用户输入负数,我希望函数通过异常返回0。
我还想知道当用户输入负数时如何显示消息,因为print()返回单元,但是函数的其余部分返回int;
发布于 2013-08-04 20:12:27
在SML中,raise和handle的优先级有点奇怪。你所写的小组
raise ((Negative "...") handle Negative msg => 0)因此,您需要在if周围添加括号以获得正确的含义。
另一方面,我不明白为什么你只是为了马上抓住它而提出一个例外。为什么不直接在else分支中返回0呢?
编辑:如果要打印某些内容,然后返回结果,请使用分号运算符:
(print "error"; 0)然而,我强烈建议不要在阶乘函数中这样做。最好将I/O和错误处理与基本的计算逻辑分开。
发布于 2013-08-04 20:23:23
下面是一些修复代码的方法:
local
fun fact 0 = 1
| fact n = n * fact (n-1)
in
(* By using the built-in exception Domain *)
fun factorial n =
if n < 0 then raise Domain else fact n
(* Or by defining factorial for negative input *)
fun factorial n =
if n < 0 then -1 * fact (-n) else fact n
(* Or by extending the type for "no result" *)
fun factorial n =
if n < 0 then NONE else SOME (fact n)
endhttps://stackoverflow.com/questions/18046773
复制相似问题