2
votes

I'm starting to learn the OCaml language. Can you please tell me why this code shows an error?

let unite x =
  if x < 100 then x mod 10
  else if x >= 100 then x mod 100;;

let dizaine x =
  if x < 100 then x / 10
  else if x >= 10 then unite(x / 10);;

let centaine x =
  if x >= 100 then x / 100;;


let somme_chiffre x =
  if x >= 100 then unite x + dizaine x + centaine x
  else if x > 9 then unite x + dizaine x
  else unite x;;

let div3 x = if ((somme_chiffre x) mod 3) = 0 then 1 else 0;;

print_int(div3 32);;
print_string("\n");;

The error is: File "./test.ml", line 3, characters 24-33: Error: This expression has type int but an expression was expected of type unit

1
FYI: I made an issue for the Reason project to try to get this error improved, because quite frankly the error message for this scenario is absolutely terrible as it is. If the error gets improved it'll hit Reason/BuckleScript first, but hopefully the entire error improvement project will eventually be upstreamed to OCaml proper. Anyway, see github.com/reasonml-community/error-message-improvement/issues/…glennsl

1 Answers

4
votes

Your last if of the unite function doesn't have an else part. You need an else part of type int to match the rest of the function.

Or, since your two tests are exhaustive and mutually exclusive, you can actually do without the second if. That would be a tidier solution.

if x < 5 then
    (* x is less than 5 in this branch *)
else
    (* x is >= 5 in this branch *)