Q123
Q123

Reputation: 319

Is there any way to keep variable value in recursive function in SML?

fun temp(x) = 
let val a = x
in if a mod (x-1) = 0 then x
   else temp(x-1)
end;

this is example Standard ML code.

What I want to know is that for example user call temp(10); then a = 10 and the temp(x-1) is called.

then the variable 'a' will change to 9. Can I keep it as 10 in Standard ML?

Upvotes: 2

Views: 1503

Answers (1)

sepp2k
sepp2k

Reputation: 370132

If your function contains val a = x, then for any invocation of temp(x), the value of a will be equal to the value of x. If you want to remember the value of a from a previous invocation when you recurse, you need to pass it around as a parameter like this:

fun temp_helper x a =
  if a mod (x-1) = 0 then x
  else temp_helper (x-1)

fun temp x = temp_helper x x

You could also make the helper function an inner function. If you do that, you can actually remove a as a parameter and instead close over a like this:

fun temp x =
let
  val a = x
  fun helper x =
    if a mod (x-1) = 0 then x
    else helper (x-1)
in
  helper x
end

Upvotes: 3

Related Questions