bryan1991
bryan1991

Reputation: 13

Why it is not possible call a function inside a while loop in OCaml?

i'm trying to use a while loop to call a function n times. I have made a simple example that return this error "Warning 10: this expression should have type unit."

let max a b =
if a > b then a else b
;;

let i = ref 0;;

while !i <= 5 do

(* function that is called i times *)
max 2 !i ;

i := !i + 1;

print_int !i

done;;

How can i call a function using while or for loop n times?

Upvotes: 1

Views: 139

Answers (1)

Andreas Rossberg
Andreas Rossberg

Reputation: 36118

It's only a warning, and it has nothing to do with the loop. It is merely pointing out that you are calling a function but ignoring its result. Usually, such a situation is an unintended bug. In the case of your example, the call to max is indeed useless.

If you want to have it nevertheless and silence the warning, you can be explicit about ignoring the result by doing

ignore (max 2 !i)

Upvotes: 7

Related Questions