OCaml 中的预期类型单位



我想打印不在哈希表中的数字,在本例中为 1、3 和 5。我收到以下错误:

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 (fun a -> if Hashtbl.mem ht a then -1 else a) l,您可以为列表中的每个元素调用一个函数。

此函数必须具有类型单元,因为将 n 个函数应用程序的结果分配给任何内容是没有意义的。

你可能想要的是

let l = [1; 2; 3; 4; 5];;
let ht = Hashtbl.create 2;;
Hashtbl.add ht 0 2;;
Hashtbl.add ht 1 4;
List.iter (fun a -> if not (Hashtbl.mem ht a) then (print_int a; print_newline ())) l

在此解决方案中,为每个变量调用打印函数。表达式"print_int (-1)"又是一个单位类型(如上所述)。

最新更新