The easiest way to do it is to use an iterator in a tail-recursive way
List.fold_left f a [b1; ...; bn] is f (... (f (f a b1) b2) ...) bn
.
let number_tr ls =
let n, _ = List.fold_left (
fun (n, pow) e -> (e * pow + n, pow * 10) (0, 1) ls in
ls
The accumulator contains two integers, the number that we are computing and the actual power. For each new element, we increment the number and then multiply the number by 10.
Another version uses a non tail-recursive iterator
List.fold_right f [a1; ...; an] b is f a1 (f a2 (... (f an b) ...))
let number_ntr ls =
List.fold_right (fun e n -> e + n * 10) ls 0
Runs :
number_tr [1; 2; 3]
> acc = (0, 1), e = 1 -> new acc = (1 * 1 + 0, 1 * 10)
> acc = (1, 10), e = 2 -> new acc = (2 * 10 + 1, 10 * 10)
> acc = (21, 100), e = 3 -> new acc = (3 * 100 + 21, 100 * 10)
> acc = (321, 1000) -> returns 321
number_ntr [1; 2; 3]
> acc = 0, e = 3 -> new acc = 3 + 0 * 10
> acc = 3, e = 2 -> new acc = 2 + 3 * 10
> acc = 32, e = 1 -> new acc = 1 + 32 * 10
> acc = 321 -> returns 321