2012-10-23 52 views
0

我正在學習標準ML,並且不斷收到此錯誤,我不知道爲什麼?爲什麼我在標準ML的這段代碼中不斷收到錯誤?

這裏是代碼和錯誤:

> fun in_list(element, list) = 
    if hd(list) = element then true 
    else val tempList = List.drop(list, 1); 
    in_list(element, tempList); 
# # Error-Expression expected but val was found 
Static Errors 

我知道必須有蹊蹺的是我想的語法。

回答

3

您需要將val值包含在let..in..end塊中。

fun in_list(element, list) = 
    if hd(list) = element then true 
    else 
     let 
      val tempList = List.drop(list, 1) 
     in 
      in_list(element, tempList) 
     end 

此外,hddrop不推薦分解列表。您應該使用模式匹配來代替。

fun in_list(element, x::xs) = 
    if x = element then true 
    else in_list(element, xs) 

有一個基本情況與空單丟失,您可以使用orelse更換if x = element then true ...。我留下他們作爲建議。

+0

哦,很酷,x :: xs是做什麼的?我知道「::」是指缺點。也如何才能讓它返回false? – cougar

+0

'::'是cons構造函數,用於將非空列表分解爲頭部'x'和尾部'xs'。列表是使用空列表'[]'和'::'構造的。例如,'[1,2,3]'實際上是'1 :: 2 :: 3 :: []'。 – pad

+0

好吧,這是有道理的,我如何得到函數返回false,如果它不是真的,因爲我們用「then」關鍵字返回真實的情況。 – cougar

相關問題