How to get a list to reduce arithmetic overflow

So yesterday, while working through some F # code as part of the coding exercise, another developer noticed something interesting. We just did a quick piece of code to demonstrate the summation of the list. If I do this:

[1..100000] |> Seq.sum 

I get the following error:

 System.OverflowException: Arithmetic operation resulted in an overflow. at <StartupCode$FSI_0003> .$FSI_0003.main@ () Stopped due to error 

However, if I do this:

 [1..100000] |> List.reduce (+) 

I get:

 val it : int = 705082704 

I understand that these two parts of the code must fulfill the same goal, they are very different. I'm just curious if there is a way to get List.reduce to throw an OverflowException instead of giving me a bad answer?

+7
f #
source share
2 answers

You can use the verified operator:

 [1..100000] |> List.reduce (Checked.(+)) 
+7
source share

From f # source code

 [<CompiledName("Sum")>] let inline sum (source: seq< (^a) >) : ^a = use e = source.GetEnumerator() let mutable acc = LanguagePrimitives.GenericZero< (^a) > while e.MoveNext() do acc <- Checked.(+) acc e.Current acc 

Note the check (operator) that checks arithmetic overflows ...

http://msdn.microsoft.com/en-us/library/vstudio/ee340296.aspx

+7
source share

All Articles