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