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

前端 未结 8 1999
太阳男子
太阳男子 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)

    0 讨论(0)
  • It is not possible to use map to reduce a list to its sum. That recursive pattern is a fold.

    sum :: [Int] -> Int
    sum = foldr (+) 0
    

    As an aside, note that you can define map as a fold as well:

    map :: (a -> b) -> ([a] -> [b])
    map f = fold (\x xs -> f x : xs) []
    

    This is because foldr is the canonical recursive function on lists.


    References: A tutorial on the universality and expressiveness of fold, Graham Hutton, J. Functional Programming 9 (4): 355–372, July 1999.

    0 讨论(0)
提交回复
热议问题