Search code examples
smlsmlnj

Making an integer value from a list that represents that integer


Hello i am attempting to write a function in SML. My goal is to create a function which takes a list that represents a value such as [2,3,4] and would return its integer representation i.e 432 (in the list the first element is the ones place).

so what my train of thought is to add each element in the list to each other..multiplying by 10^n where n is increasing by one each time

for example [2,3,4] -> 2*10^0 + 3*10^1 +4* 10^2 = 432..im not sure how to do this recursively but this is what I have

fun List2Integer nil = 0
  | List2Integer (x::xs) = x * (power (10,1)) + (List2Integer xs);

I know that right now it doesn't work since x is always getting multiplied by 10^1 where 1 is not increasing.

thanks for taking the time to read this..I would appreciate any hints


Solution

  • fun toInt [] = 0
      | toInt (x :: xs) = x + 10 * (toInt xs)
    

    To compute the right number out of a list of digits [a0, a1, a2, a3, ...] you just need to compute the sum a0 + a1*10 + a2*10*10 + a3*10*10*10 + .... Then you can left-factor-out 10 and get an expression of the form a0 + 10*(a1 + 10*(a2 + 10*(a3 + 10*(...)))) which is exactly what the function above does.