0

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

Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
user4348719
  • 351
  • 1
  • 2
  • 13

1 Answers1

1
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.

gruenewa
  • 1,666
  • 11
  • 16
  • could you possibly walk through how/why it works? I'm not quite sure I understand how just adding 10 to each element would add up to the right number. – user4348719 Feb 06 '15 at 19:03