I want to change some code written in C into Ocaml
Here is a C code
int a, b;
if(m > n)
{
a = n;
b = m;
}
else
{
a = m;
b = n;
}
and I tried to change it into Ocaml but somehow I got a syntax error at the second line.
let rec gcd m n =
if m > n then begin let a = n in; let b = m in end
else begin let a = m in; let b = n in end
What is the problem and how can I fix it?
You have to understand that let declarations are local. That is, when you write let variable = assignment in expression
, variable
is only bound in the scope of expression
Now when you write begin let a = n in; let b = m in end
, not only your variable won't be bound outside of the block, but the compiler is still waiting for an expression after both in
words. You have to remember that unless you're using imperative features of OCaml, ;
is not something you should ever write to indicate subsequent calculations.
Note also that every let
declaration will create a new variable, so if you type let a=
in two different places of your code, this is not the same a. Hence, the let
must be exterior to your if
statement:
let (a,b) =
if m > n
then (n,m)
else (m,n)
in
the rest of your code