As many of you already know, Ocaml's error messaging is really bad and I am stuck. I tried to search the problem, but the error message was too vague to search for. The following code is supposed to filter out all of the numbers that are above a certain threshold using recursion.
let rec list_above thresh lst =
if lst = [] then
printf("Herewego");
else
begin
if (List.hd lst) >= thresh then
(((List.hd lst)::(list_above thresh List.tl lst)))
else if (List.hd lst) < thresh then
((list_above thresh List.tl lst));
end
;;
It keeps saying that there is a syntax error on line 53, which is the line with the first else, but I can't see anything wrong with my if and else statement.
The ;
operator in OCaml is used to separate two values. But there is no second value after the first ;
in your code.
You may be used to ;
in other languages like C, where ;
is used to terminate all expression statements.
To fix the syntax error, remove the first ;
in this code.
After fixing this error, you have a type error. There are two values returned (in different cases) by your function. One is returned by the printf
call. It returns a value of type unit
(because it doesn't really compute a value). The other is returned by the list expression (((List.hd lst)::(list_above thresh List.tl lst)))
. This value is some sort of list.
Because unit
is not a list type, this code can't be correct. A function has to return values of the same type in all cases.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.