Return Changed value of Parameter in OCAML

156 Views Asked by At
let rule1 m = 
    m = m/2;
    m

rule1(250) should return 125 but instead returns 250.

How is it possible to return an updated value of a parameter?

2

There are 2 best solutions below

2
MaartenDev On BEST ANSWER

Are you sure m is mutable? The m = .. statement will not update the provided argument. Would returning the updated value be an option?

let rule1 m = 
    m/2
0
Chris On

If you genuinely wish to mutate the value of a binding, that binding has to be a ref or a record type with a mutable field (which a ref is one specific example of with handy syntactic sugar.)

let m = ref 12 in
  (m := !m / 2;
   print_int !m;
   print_newline ())

However, using mutable state like this likely means you're writing non-idiomatic OCaml code, and there is something you're missing: either a more elegant solution, or in the case of learning, the point of an algorithm lesson.

Or usually both, of course. I speak from personal experience.