This is my variant
import Data.List
decimal :: [Int] -> Int
decimal xs = foldl' (\sum (pos,x) -> (sum + x*(10^(l-pos)))) 0 $ zip [1..] xs where
l = length xs
*Main> decimal [1,4,3,1,9]
14319
In Haskell
, you have really powerfull weapon - functions for lists processing. One of these functions is foldl
(we use strict version of foldl
, foldl'
) It's type
foldl :: (a -> b -> a) -> a -> [b] -> a
This functions takes thre arguments, an accumulating agrument, a list processed, and, the most interest,
the function that perform any operation with accumulator and list element and returns the result. Fold is really significant function so you should read detail manual about it.
But, there is a problem, we have three variables it our equation: list element processed (x
), total list length (n
) and position of processed element (k
). But we can traverse to foldl
only one element.
How can we traverse position of each element? Let's form tuples from Int
where first element is a position, and second is a value. It is a standard trick, zip
function helps us:
zip [1..] [1,4,3,4,6]
[(1,1),(2,4),(3,3),(4,4),(5,6)]
Than we pass our list of tuples into foldl
function, and foldl
call lambda function
(\sum (pos,x) -> (sum + x*(10^(l-pos))))
for each element of list, summing result in sum