2

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.

John Kerry
  • 45
  • 6
  • I'm linking this question to an older one which addresses the main problem here, just for the sake of cross-referencing. – duplode Mar 31 '20 at 12:34

1 Answers1

5

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
Harald Gliebe
  • 7,236
  • 3
  • 33
  • 38
  • how does compiler know which elements a and e are in the array? is this a point free shorthand? – wide_eyed_pupil May 05 '21 at 08:00
  • @wide_eyed_pupil check the type of `foldl' :: (a -> b -> a) -> a -> [b] -> a` , it takes a function that combines the accumulator of type `a` and a value of the array of type `b` and produces a new `a`. – Harald Gliebe May 05 '21 at 08:12