0
votes

Okay hi guys, I am having a weird problem.

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

The code above does not work, because trying to compile I am getting the error, that expected type '[Int]' could not be matched with actual type 'Int'. I don't get that.

Fun Fact: when I delete the signature, the function works fine! Does anybody know the fault?

Thank you!

1
foldr (+) 0 :: Num a => [a] -> a. When you omit the type signature, the correct type for hist is inferred. If you want to specify a concrete type, it should be [Int] -> Int.chepner
Hint: what is the return type of foldr (+) 0? (You can ask GHCi if you're not sure.)Robin Zigmond

1 Answers

4
votes

The output of the foldr (+) 0 x will be an Int, not an [Int]. If you want a list, you can use scanl, but I guess, you still want foldr:

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

I however strongly advise to make use of sum :: (Foldable f, Num a) => f a -> a which also calculates the sum, but on all types that are instances of Num, and for all Foldables (and thus not only a list).