Dagoo Mong
Dagoo Mong

Reputation: 107

Ocaml syntax error in a simple if-then-else

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?

Upvotes: 0

Views: 1969

Answers (2)

V. Michel
V. Michel

Reputation: 1619

If you wan't, you can do quite the same:

let m=3 and n=4 in

let a=ref 0 and b=ref 0 in
if(m > n)
then
(
    a:=n;
    b:=m;
)
else
(
    a:=m;
    b:=n;
);

Printf.printf "a=%d b=%d\n" !a !b;;

Upvotes: 1

PatJ
PatJ

Reputation: 6140

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

Upvotes: 7

Related Questions