2

I'm trying to write a function dec2int that converts a list of integers to an integer number. My only constraint is that I must use foldl.

The type signature for the function is:

dec2int :: [Int] -> Int

The function should work in this way:

Input:  dec2int [2,3,4,5]
Output: 2345

I found a working solution here that I understand:

dec2int' = foldl (\x y -> 10*x +y) 0

I tried to write my own solution, using foldl as required:

dec2int xs = foldl (\a b -> a + (b*(10^(l-1)))) 0 xs
                  where l = length xs

However, I get this error:

ghci> dec2int [1,1]
20

I realised the value of length xs must be constant. However, I want the value to vary for my function.

I wanted to function to work in this way

0 + 1*10^((length [1,1])-1) = 10 = v
10 + 1 *10^((length [1])-1) = 11

How do I refer to the list during the recursion? I want the value of length xs to change each time foldl is called recursively?

Dave B
  • 23
  • 2
  • 4
    The `dec2int' = foldl (\x y -> 10*x +y) 0` looks like the only simple solution. By working with powers we need to work with an index, and will make the function less readable. – Willem Van Onsem Jun 19 '21 at 11:14

1 Answers1

1

You can keep track of the index in the step function of the fold:

dec2int xs = snd $ foldl (\(i, a) b -> (i + 1, a + b * 10 ^ (l - i))) (1, 0) xs
  where l = length xs

But, as Willem van Onsem says, this is more complicated than it needs to be.

Noughtmare
  • 9,410
  • 1
  • 12
  • 38