2013-04-08 107 views
1

我們的教授要求我們做這在分配中:如何引發打印消息並返回值的異常?

If the threshold given is negative, you should print the message 「Error: Negative Threshold」 and return an empty list. To do this, define an exception called ThresholdOutOfRange, raise it if the threshold is negative, and handle the exception to achieve the proper behavior.

我不知道如何拋出一個異常,返回值,並打印錯誤消息。現在我的籌集異常代碼是(剛剛與異常的重要位):

fun getnearbylist(center, threshold, ziplist) = 
    let 
     exception ThresholdOutOfRange; 
     fun test_threshold(threshold, zip, nil) =nil 
     | test_threshold(threshold, zip, ziplist as x::xs) = 
      if (threshold <0.0) then raise ThresholdOutOfRange 
(*  [...skipped a long unrelated middle bit. most important is just knowing 
       this function returns a string list...] *) 
      else x::test_threshold(threshold, zip, xs) 
    in 
     test_threshold(threshold, center, ziplist) 
     handle 
     ThresholdOutOfRange => [] 
    end 

因此,當引發異常我的代碼將只返回一個空列表。鑑於異常必須具有與我所知道的函數相同的返回類型,我該如何才能返回空列表並輸出錯誤消息?

回答

3

異常處理的結果類型必須與處理異常的表達式相同,也就是說,exp_1exp_2在下面的代碼中必須具有相同的類型,就像「那麼「和」其他「部分的if-表達式。

exp_1 handle pat => exp_2 

那麼你正在尋找的是在exp_2部分做多件事情的方式,特別是一些具有打印信息的副作用。對於這樣的事情,你可以使用序列。一個序列具有以下形式(注意括號)

(exp_1; ... ; exp_n) 

它本身就是一個表達式。這表現在以下

- (print "foo\n"; print "bar\n"; 42); 
foo 
bar 
val it = 42 : int 

從這一點我們可以看出,一個序列的最終結果是什麼都exp_n評估爲。

由於序列在鬆懈表達式經常使用的,它是允許寫入以下(不含先前提到的括號)

let dec in exp_1 ; ... ; exp_n end 

獎金信息

序列實際上是一個派生形式(語法糖)的一系列案件。下面

(expr_1 ; ... ; exp_n ; exp) 

相當於

case expr_1 of _ => 
    case ... => 
    case exp_n of _ => exp 
+0

我相信這也被稱爲'副effecting' – eazar001 2013-04-09 23:55:12

1
  • 首先聲明一個例外

    exception OutOfRangeException; 
    
  • 定義將引發異常的函數:

    fun someFunc x = 
        if x < 0 then 
        raise OutOfRangeException 
        else [1,2,3,4] (*return some list*) 
    
  • 最後,將通過打印消息並返回 和空單處理異常的函數:

fun someFunc_test x=  
    (someFunc x) handle OutOfRangeException => (print "exception"; []) 
+0

的異常不需要是全局的。它只是需要在代碼的範圍內處理它 – 2013-04-10 15:26:39

+0

@ Jesper.Reenberg我剛纔提到它是一種很好的做法。 – tarrsalah 2013-04-11 21:28:50

+0

好吧,這不一定是好的做法。保持用戶隱藏的異常可能有各種原因。例如,內部邏輯可以通過異常處理來實現,並且給予用戶對異常的訪問權限可能會使其失效。 一般而言,只要異常將被內部使用,就沒有必要通過聲明「全局」來污染環境。 – 2013-04-12 01:59:02