I know that let rec is used when I want recursive.
For example,
let rec power i x = if i = 0 then 1.0 else x *. (power (i-1) x);;
Ok, I understand that.
But how about this one:
let x y = y + y in x 2?
Should I use rec inside?
I think I should, because it has x 2 inside, loading itself, but it seems it is fine with compiler.
So when I should use let rec and shouldn’t?
Also, what is the difference between
let (-) x y = y - x in 1-2-3;;
and
let rec (-) x y = y - x in 1-2-3;;
Are they both legal?
You need to understand the scoping rules of OCaml first.
When you write
let f XXX = YYY in ZZZ, if you usefinYYYthen you needrec. In both cases (ie with or withoutrec),fwill be defined inZZZ.So:
is perfectly valid.
For you second question: no it is not equivalent, if you try it on the toplevel, the second statement loop for ever and is equivalent to
let rec loop x y = loop y x in (). To understand why it is looping for ever, you can understand the application ofloopas an expansion where the identifier is replaced by its body. so:So
loopbody isfunction x y -> loop y x, which can be expanded tofunction x y -> (function a b -> loop b a) y x(I’ve renamed the parameter names to avoid ambiguity), which is equivalent tofunction x y -> loop x ywhen you apply the body and so on and so on. So this function never does anything, it just loops forever by trying to expand/apply its body and swapping its arguments.