Search code examples
functionmathlanguage-agnosticsumlanguage-design

Right behavior for variable-arity sum function


I'm defining a variable-arity sum function for a toy language. It seems natural to me to allow it to be called without arguments and return 0, but real languages (and their implementations) disagree among themselves.

Is there a use-case where returning zero would be less correct than throwing an exception?


Solution

  • Mathematically speaking, the empty sum (the sum of no numbers) is defined to be zero. To be mathematically correct, returning zero seems like the proper choice here. Throwing an exception in this case would potentially complicate the use of your function, since you would have to be sure to guard each call with a try/catch in case you provide zero arguments somehow.

    Hope this helps!