ELM recursive iteration

Hi there,
I have a function computeNextValue such as for a given number x, it computes the number y, by additioning all digits of number x to itself
ex : Given x = 45: y = 54 = 4 + 5 + 45

computeNextValue : Int → Int
computeNextValue x =
List.sum (numberToList x) + x

and i want to mplement the function computeNextValueWithIteration with the following signature :

computeNextValueWithIteration : Int → Int → Int

The first parameter will be an “iteration” value, the second parameter will be the “number” value such that I compute “iteration” number of times to get the result y.

ex : Given x = 123 and iteration = 3, you would compute why like this :

  • Iteration 1 : 129 = 1 + 2 + 3 + 123
  • Iteration 2 : 141 = 1 + 2 + 9 + 129
  • Iteration 3 : 147 = 1 + 4 + 1 + 141

y = 147

can you please give me a feedback about my function computeNextValueWithIteration

computeNextValueWithIteration : Int → Int → Int
computeNextValueWithIteration n x=
case n of
1-> computeNextValue x
_-> computeNextValueWithIteration (n - 1) (computeNextValue x)

thank youu

Quick tip:
To make it easier to read code here you can do this:
format as code

The other way you could have done this is something like this:

computeNextValueWithIteration : Int -> Int -> Int
computeNextValueWithIteration n x =
    List.foldl (\_ sum -> computeNextValue sum) x (List.repeat n 0)

That is creating a list the length of iterations. (what is in the list is not important)
And then fold that list with your function.

You could also make it shorter but more cryptic by creating a list of the function you want to apply and folding over the list of functions:

computeNextValueWithIteration : Int -> Int -> Int
computeNextValueWithIteration n x =
    List.foldl (<|) x (List.repeat n computeNextValue)

But I think your initial version is easier to read/understand.
and it is usually better to make it easier to read/understand next month than to have the shortest amount of text.

2 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.