This may be a very newbie question, but I didn't find the answer. I need to store, for example a list and later replace it with another, under the same pointer.
Asked
Active
Viewed 8,215 times
1 Answers
14
It can be done via references:
let fact n =
let result = ref 1 in (* initialize an int ref *)
for i = 2 to n do
result := i * !result (* reassign an int ref *)
done;
!result
You do not see references very often because you can do the same thing using immutable values inside recursion or high-order functions:
let fact n =
let rec loop i acc =
if i > n then acc
else loop (i+1) (i*acc) in
loop 2 1
Side-effect free solutions are preferred since they are easier to reason about and easier to ensure correctness.

pad
- 41,040
- 7
- 92
- 166
-
Thanks. Can you explain me the meaning of ref 0 ? – EBM Apr 03 '12 at 23:13
-
3See the link I refer to in my answer. Basically `ref 0` is a record `{mutable contents: int}` with `contents` initialized by `0` and `contents` could be reassigned later. – pad Apr 03 '12 at 23:21