0
我要打印不在哈希表的數字,在這種情況下,1,3和5我'得到以下錯誤:期待型單元OCaml中
This expression has type int but an expression was expected of type
單元
爲什麼它期望類型單位?
let l = [1; 2; 3; 4; 5];;
let ht = Hashtbl.create 2;;
Hashtbl.add ht 0 2;;
Hashtbl.add ht 1 4;
let n = List.iter (fun a -> if Hashtbl.mem ht a then -1 else a) l in
if n > 0 then print_int a;;
「* ...打印不在散列表中的數字... *」 - 這意味着傳遞給List.iter的lambda看起來應該如下所示:fun a - > if if(Hashtbl.mem ht a)then(print_int a; print_newline())' –
@AntonTrunov感謝提示,重讀那部分:) 我用你的行更新了我的verison。現在它是正確的! –
另一種說法是'List.iter'是一個必要的構造;迭代的函數只能起副作用。相反,'List.map'是一個功能性構造。 – user3240588