使用foldl计算产品总和
基本上,我希望用以下算法计算一个列表:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要使用
foldl
进行此操作,我们需要考虑在遍历列表时需要保持哪些状态。在这种情况下,我们需要当前项目的索引(从0开始)和当前总和(也从0开始)。我们可以将它们都存放在元组中。
在每个步骤中,我们将当前索引乘以当前值乘以总和,并将索引增加1。
完成折叠后,我们可以丢弃索引并返回总和。
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.