3

I have a function that returns [Int] and I would like to take the sum of the list. However, while each individual element is smaller than maxBound::Int, the sum is definitely larger.

A (contrived) exmple:

ghci> sum ([1..10000000] :: [Int])
-2004260032

Is there any way to force sum to accumulate into an Integer instead of an Int? Am I thinking about this wrong?

Wilduck
  • 13,822
  • 10
  • 58
  • 90

1 Answers1

11

sum returns the same type as its input list elements:

sum :: Num a => [a] -> a

so you need to pass it a [Integer] in order to return an Integer. If your input list is already of type [Int], you can use the function:

sum . map fromIntegral

instead:

ghci> sum . map fromIntegral $ ([1..10000000] :: [Int])
50000005000000
Conrad Parker
  • 854
  • 10
  • 23