使用foldl计算产品总和

发布于 2025-02-04 08:21:01 字数 392 浏览 2 评论 0原文

基本上,我希望用以下算法计算一个列表:

myList = [a1,a2,a3,... a8] - 所有元素is int int int

= a [n] * n(其中n是从0开始的索引)

结果= a1*0 + a2*1 + a3*2 .... + a8*7

以下代码有效。

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

但是,我被要求使用foldl实施它,但我尝试过但没有做到。谁能建议解决方案?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拥抱没勇气 2025-02-11 08:21:01

要使用foldl进行此操作,我们需要考虑在遍历列表时需要保持哪些状态。

在这种情况下,我们需要当前项目的索引(从0开始)和当前总和(也从0开始)。我们可以将它们都存放在元组中。

在每个步骤中,我们将当前索引乘以当前值乘以总和,并将索引增加1。

完成折叠后,我们可以丢弃索引并返回总和。

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文