2015-06-11 34 views
1

我試圖獲取SML中整數列表的最後一個元素,但我想指出(以某種方式)用戶傳入不可接受的列表(如空的列表)時。我的代碼在這裏:標準ML:獲取列表中的最後一個

fun lastInList [] = ~1 
    | lastInList [x] = x 
    | lastInList (x::xs) = 
    lastInList xs; 

這適用於任何非空列表,因爲執行總是會在第一行之前執行。但是,有沒有一種能夠處理所有整數的習慣方式?我想回到某種例外。當前的解決方案並不是很好,因爲-1可以在我的列表中(顯然)。

感謝您的幫助, bclayman

+3

聽起來像你的問題不是如何獲得列表中的最後一個元素,而是如何區分特定結果(本例中爲空列表)與域中的任意數據元素(本例中爲整數)。我建議改寫你的問題以反映你的意圖。 – Gabe

回答

3

您可以隨時raise an exception

fun last []  = raise Empty 
    | last (x::xs) = last' x xs 

fun last' x []  = x 
    | last' _ (x::xs) = last' x xs 

另一個option(如果你會原諒雙關語):

fun last []  = NONE 
    | last (x::xs) = SOME (last' x xs) 

fun last' x []  = x 
    | last' _ (x::xs) = last' x xs 

希望有所幫助。

+1

引發的習慣異常是預定義的'Empty',它也被其他列表函數使用。 –

2

的慣用方法是要麼只是允許函數失敗的無效輸入:

fun last []  = raise Empty 
    | last [x]  = x 
    | last (_::xs) = last xs 

或者使用一個選項類型:

fun last' []  = NONE 
    | last' [x]  = SOME x 
    | last' (_::xs) = last' xs 

這也適用於任何泛型列表,不僅僅是整數。

+2

非窮舉模式非常沮喪。明確提出一個例外。 –