DanLeo
DanLeo

Reputation: 23

OCaml A ref does not change its value despite I instructed it

I have a real code but I made this sample to illustrate my issue. This is the code sample:

let ejem n =
  let count = ref 0 in
  let rec aum n =
    if n = 0 then 0
      else (count := !count + 1; n + aum (n-1) )
  in (aum n, !count)

I try to change the count value inside aum function but, despite the count is outside of this function, its value is always 0 once it finishes.

Please, help me to get what the issue is

Upvotes: 2

Views: 183

Answers (2)

Oliver
Oliver

Reputation: 997

In addition to Jeffrey's answer, you could use the more idiomatic incr count instead of count := !count + 1 and pred n instead of n - 1. These functions are defined in the always opened Stdlib module.
You could even convert the recursive function aum to a tail-recursive function using an accumulator.

The improved ejem function will then be:

let ejem n =
  let count = ref 0 in
  let rec aum accu n =
    if n = 0 then
      accu
    else (
      incr count;
      aum (accu + n) (pred n)
    )
  in
  let res = aum 0 n in
  (res, !count)

Upvotes: 1

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

OCaml doesn't guarantee any particular order of evaluating expressions.

In your last line you have this expression:

(aum n, !count)

It's completely legitimate for OCaml to evaluate the !count before the aum n, which will give the result you see.

To control evaluation order you can use let:

let res = aum n in
(res, !count)

Upvotes: 7

Related Questions