Issue with the length function in Haskell

Viewed 85

I am trying to write a function in Haskell that will take a list of integers eg [1,2,3,4,5] and convert them into a number eg 12345 using recursion. I'm using the length function in the standard library of Haskell to calculate what place the digit is so they can be added all together (10000+2000+300+40+5). However, when I use length to calculate the length of the list, it is always 1 no matter what and I am not sure why. Here is my code:

dig :: [Integer] -> Integer
dig [] = 0
dig (x:xs) = x * (10^(fromIntegral(length[xs]))) + fromDigits(xs)

Running this code will always just multiply the digit by 10 and length is always 1, so dig [1,2,3,4] gives 100 instead of 1234.

1 Answers

With [xs] you are putting the xs in a new one-element list, so the length is one.

Just use length xs instead.

A simpler approach would be with by multiplying the accumulated result by 10 for each recursion step:

dig :: [Integer] -> Integer
dig = foldl' (\a e -> 10 * a + e) 0
Related