Home > other >  Using foldl to calculate the product sum
Using foldl to calculate the product sum

Time:06-05

Basically, I wish to calculate a list with the algorithm as below:

myList = [a1, a2, a3, ... a8] -- all elements are Int

result = a[n] * n (where n is index starting from 0)

result = a1*0 a2*1 a3*2 .... a8*7

The below code works.

prodSum xs = helper 0 xs
    where helper a (x:xs) = 
              let a' = (a   1)
              in a * x   helper a' xs
          helper a _ = 0

However, I was asked to implement it using foldl, and I tried but did not make it. Can anyone suggest a solution?

CodePudding user response:

To do this with just foldl, we need to consider what state we need to keep while traversing the list.

In this case, we need the index of the current item (which starts at 0) and the current sum (which also starts at 0). We can store both of them in a tuple.

On every step, we add the current index multiplied by current value to the sum, and increment the index by 1.

After the foldl is done, we can discard the index and return the sum.

Prelude> prodSum = fst . foldl (\(sum, i) x -> (sum   x * i, i   1)) (0, 0)
Prelude> prodSum [1..2]
2
Prelude> prodSum [1..5]
40
Prelude> prodSum [1..8]
168
  • Related