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

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

问题描述

Haskell

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

我能够使用 sum 函数获得列表的总和,但是是否可以使用 map 函数获得列表的总和?还有map函数有什么用?

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?

推荐答案

你不能真正使用 map 来总结一个列表,因为 map 将每个列表元素独立于其他元素.例如,您可以使用 map 来增加列表中的每个值,如

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]

实现 addm 的另一种方法是使用 折叠:

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

addm' = foldl (+) 0

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

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