0
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

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
  • 2
    Indeed you need to use `fsum x = ...` and you can't pattern match on `x` -- but you can use the [methods of the `Foldable` class](https://hackage.haskell.org/package/base-4.17.0.0/docs/Data-Foldable.html#t:Foldable) like `foldr` and `foldl`, so ... (well, even `sum` is a method but I think you want to avoid that). – chi Oct 25 '22 at 00:21
  • 1
    Thanks it finally clicked after two hours :) – RunTimeError31415 Oct 25 '22 at 00:35
  • In general, it if you only assume `Foldable f`, you have to use methods of the `Foldable` dataclass to operate on `f`. – jthulhu Oct 25 '22 at 10:59

1 Answers1

0

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
Andreas
  • 13
  • 1
  • 5