How can I write the fsum foldable function in haskell?

133 Views Asked by At
fsum :: (Foldable f, Num a) ⇒ f a → a 

It computes the sum of all numbers in a container-like data structure. My problem is that I cannot define f a as a list or Maybe or any other foldable types to have access. So I am assuming I should write

fsum x = ....

But I have no clue how to fold it given that a is not a monoid. Any opinions? Thanks in advance

1

There are 1 best solutions below

0
Andreas On

This was already answered in the comments. But here is some sample code:

main = do
  putStrLn $ show $ fsum [0,1,2]
  putStrLn $ show $ fsum (Just 4)

fsum :: (Foldable f, Num a) => f a -> a 
fsum = foldr (+) 0