计算Haskell中的列表累计和 [英] Calculating list cumulative sum in Haskell

查看:108
本文介绍了计算Haskell中的列表累计和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个返回列表运行总和的函数。例如运行[1,2,3,5]是[1,3,6,11]。我写这个函数的下面,它可以返回列表中所有值的最终总和。那么我怎么能一个接一个地分开它们?

  sumlist'xx = aux xx 0 
其中aux [] a = a
aux(x:xs)a =辅助xs(a + x)
a +>
  sumlist'x 到每个步骤的结果并使用空列表作为基本情况: xx = aux xx 0 
其中aux [] a = []
aux(x:xs)a =(a + x):aux xs(a + x)

然而,Haskell更习惯于将这种事物表现为折叠或扫描。


Write a function that returns the running sum of list. e.g. running [1,2,3,5] is [1,3,6,11]. I write this function below which just can return the final sum of all the values among the list.So how can i separate them one by one?

sumlist' xx=aux xx 0
    where aux [] a=a
          aux (x:xs) a=aux xs (a+x)

解决方案

You can adjust your function to produce a list by simply prepending a+x to the result on each step and using the empty list as the base case:

sumlist' xx = aux xx 0
    where aux [] a = []
          aux (x:xs) a = (a+x) : aux xs (a+x)

However it is more idiomatic Haskell to express this kind of thing as a fold or scan.

这篇关于计算Haskell中的列表累计和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆