Reputation: 25812
Well, I have problems in using semicolon (single and double)
and nested if else
in OCaml.
For example
let union u p q =
let rec unionfy id_ary i =
if i < Array.length id_ary then begin
if id_ary.(i) = p then begin
id_ary.(i) <- id_ary.(q);
print_array id_ary 0;
end
unionfy id_ary (i + 1);
end
else print_string "end of union";
in
unionfy u.id_ary 0;;
The compiler said line 18, characters 29-95:
Error: This expression is not a function; it cannot be applied
The line which has problem is if id_ary.(i) = p then begin
, but I don't see why.
Also, can anyone tell me more about semicolon
thing and nested if else
?
here are some questions in my mind:
single semicolon
? If I use it for more than one expressions, will I have to add a double semicolon
after the last expression?Can I use multiple begin end
inside nested if
?
It seems I don't need to add else
if the result is unit and do nothing
?
Upvotes: 0
Views: 4669
Reputation: 47934
The problem is end
. The entire if
expression should return unit
in this case, so you need a semi-colon at the end of the expression. The other end
doesn't need it since the if
expression is continuing with the else
clause. Below, I've removed the unnecessary semi-colons and added the remaining one,
let union u p q =
let rec unionfy id_ary i =
if i < Array.length id_ary then begin
if id_ary.(i) = p then begin
id_ary.(i) <- id_ary.(q);
print_array id_ary 0
end;
unionfy id_ary (i + 1)
end
else print_string "end of union"
in
unionfy u.id_ary 0;;
EDIT: The 'rule' is really the definition of the semi-colon in OCaml. It separates sequential expressions that return unit
. The content between begin ... end
is a singular expression. The entire if
expression is also an expression, but made up of multiple expressions. So the two statements contained in the first if
statement are,
if id_ary.(i) = p then begin ... end;
unionfy id_ary (i + 1)
Upvotes: 5