使用Haskell的映射函数来计算列表的总和 [英] Using Haskell's map function to calculate the sum of a list

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

问题描述

Haskell

  addm :: [Int]  - > Int 
addm (x:xs)= sum(x:xs)

我能够实现以获得总和列表使用 sum 函数,但可以使用 map 函数获取列表的总和吗?另外还有什么使用map函数的?

解决方案

你真的不能使用 map 来总结一个列表,因为map将每个列表元素与其他列表元素分开处理。例如,您可以使用 map 来增加列表中的每个值,如

  map(+1)[1,2,3,4]  - 给出[2,3,4,5] 

另一种实现你的addm的方法是使用 foldl

  addm'= foldl(+)0 


Haskell

addm::[Int]->Int
addm (x:xs) = sum(x:xs)

I was able to achieve to get a sum of a list using sum function but is it possible to get the sum of a list using map function? Also what the use of map function?

解决方案

You can't really use map to sum up a list, because map treats each list element independently from the others. You can use map for example to increment each value in a list like in

map (+1) [1,2,3,4] -- gives [2,3,4,5]

Another way to implement your addm would be to use foldl:

addm' = foldl (+) 0

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

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