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

前端 未结 8 2062
太阳男子
太阳男子 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 16:57

    map can never be the primary tool for summing the elements of a container, in much the same way that a screwdriver can never be the primary tool for watching a movie. But you can use a screwdriver to fix a movie projector. If you really want, you can write

    import Data.Monoid
    import Data.Foldable
    
    mySum :: (Foldable f, Functor f, Num a)
          => f a -> a
    mySum = getSum . fold . fmap Sum
    

    Of course, this is silly. You can get a more general, and possibly more efficient, version:

    mySum' :: (Foldable f, Num a) => f a -> a
    mySum' = getSum . foldMap Sum
    

    Or better, just use sum, because its actually made for the job.

提交回复
热议问题