Using Haskell's map function to calculate the sum of a list

前端 未结 8 2044
太阳男子
太阳男子 2020-11-28 16:29

Haskell

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

I was able to achieve to get a sum of a list using sum fu

8条回答
  •  暖寄归人
    2020-11-28 17:09

    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
    

提交回复
热议问题