我們的教授要求我們做這在分配中:如何引發打印消息並返回值的異常?
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
因此,當引發異常我的代碼將只返回一個空列表。鑑於異常必須具有與我所知道的函數相同的返回類型,我該如何才能返回空列表並輸出錯誤消息?
我相信這也被稱爲'副effecting' – eazar001 2013-04-09 23:55:12