How To Get List Reduce To Throw Arithmetic Overflow

f#

Solution

You can use a checked operator:

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

Problem

So, yesterday while working through some F# code as part of a coding exercise, another developer pointed out something interesting. We were just doing a quick piece of code to demonstrate summing a list. If I do: ``` [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: ``` [1..100000] |> List.reduce (+) ``` I get: ``` val it : int = 705082704 ``` I realize although these two pieces of code should accomplish the same purpose they are very different. I am just curious is there a way to get the List.reduce to throw the OverflowException rather than giving me a bad answer?

Original source