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?

1
  • 2
    Is sum $ map fromIntegral an appropriate way to do this? Commented Oct 5, 2012 at 1:06

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

3 Comments

Hahaha, I came to the same conclusion just a few seconds before you posted this. Wonderful.
I'm surprised this works, given that the type is :: Num a => a. Is this GHCi's type defaulting coming in to play?
@Matt Fenwick: Yes, Integer is used by default for Num a => a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.