I'm trying to write a simple Ocaml function but im getting this error:
Error: This expression has type unit but an expression was expected of type int
let rec euclid a b =
if a = b then a
else if a < b then 1
else if a > b then 2
To fix the immediate problem, you need else
clauses in your function:
let rec euclid a b =
if a = b then a
else if a < b then 1
else 2 (* You know a > b is the only possible alternative *)
You may realize this, but this function is not recursive, nor, I think, is it doing what you want it to do.
However, there is an error in the way you're conceptualizing how a function works in Ocaml. The way you've written the function is imperative in nature; it is a series of if/then
statements which are acted upon sequentially. Rather, the return value of euclid
should be simply the result of one broad if/then
statement (an integer value). Nesting, as I have done above, can be acceptable, but the essential thing to take away is that a function is just a single expression which is evaluated, not a series of imperative actions.
EDIT for updated question:
All OCaml if/then
statements should have else
clauses. Your very last nested if/then
statement has no else
clause. If OCaml detects an if/then
statement with no else
clause, an else
clause is assumed returning ()
(unit). Essentially, if a > b
is false, what should OCaml return? It assumes nothing, but returning ()
conflicts with the supposed type of your function (an integer).
Of course, that a > b
is false is impossible in your function, since if not a = b
and not a < b
, the only other choice is a > b
. Thus, you don't need another if
statement at the end of your function; at that point, you know without a doubt that a > b
, so you can simply say else 2
.