0
votes

I want to print the numbers that are not in the hashtable, in this case 1, 3 and 5. I'am getting the following error:

This expression has type int but an expression was expected of type unit

Why does it expect type unit?

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;;
1

1 Answers

0
votes

With the line List.iter (fun a -> if Hashtbl.mem ht a then -1 else a) l you call a function for every element in a list.

This function has to have type unit, because it wouldn't make sense to assign the results of n function applications to anything.

What you may want is

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

In this solution, you call the print-function for every variable. The expression "print_int (-1)" is again a unit-type (like described above).