1

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?

4

1 回答 1

7

You need to understand the scoping rules of OCaml first.

When you write let f XXX = YYY in ZZZ, if you use f in YYY then you need rec. In both cases (ie with or without rec),f will be defined in ZZZ.

So:

let x y = y + y in
x 2

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 of loop as an expansion where the identifier is replaced by its body. so:

So loop body is function x y -> loop y x, which can be expanded to function x y -> (function a b -> loop b a) y x (I've renamed the parameter names to avoid ambiguity), which is equivalent to function x y -> loop x y when 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.

于 2012-12-04T10:40:05.060 回答