2013-08-04 58 views
1

我有以下代码:标准ML异常

- 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;

回答

4

raisehandle的优先级在SML中有点奇怪。你已经写了群体作为

raise ((Negative "...") handle Negative msg => 0) 

结果是什么,你需要添加if加上括号,以获得正确的含义。

另一方面,我不明白为什么你举一个例外只是为了赶上它。为什么不简单地在else分支中返回0?

编辑:如果你要打印的东西,然后返回结果,使用分号操作:

(print "error"; 0) 

不过,我会强烈建议不要这么做阶乘函数内。最好将I/O和错误处理与基本的计算逻辑分开。

1

这里有许多方法可以解决您的代码:

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) 
end