2013-08-04 59 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