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

前端 未结 8 2045
太阳男子
太阳男子 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:12

    Map "maps" each element of your list to an element in your output:

    let f(x) = x*x
    map f [1,2,3]
    

    This will return a list of the squares.

    To sum all elements in a list, use fold:

    foldl (+) 0 [1,2,3]
    

    + is the function you want to apply, and 0 is the initial value (0 for sum, 1 for product etc)

提交回复
热议问题