Note that this will be relatively slow in Julia because it is type unstable. Why not just return a Float64 in all cases?
(Contrary to popular misconception, integers are represented exactly by Float64 values, up to \pm 2^{53}, so you don’t generally improve accuracy by using Int to store integers.)
Well the stacktrace actually also tells you what went wrong and how to fix it right on the top:
julia> sum(float∘f, String[])
ERROR: MethodError: reducing over an empty collection is not allowed; consider supplying `init` to the reducer
Stacktrace:
...
Thank you, I was not aware of this, and according to this thread+, -, *, / and sqrt all preserve this precision. I will certainly consider this in the future, but I do need to work on being comfortable with this after 30 years of having the “misconception”.
Thanks for challenging my old habits, it is nice to see a well respected programmer confident in using Float64 to represent integers. I will keep this in mind in the future, but right now I prefer not to change that part of the code.
Not much, on my benchmarks it is even a bit slower. But the underlying idea remains interesting: preserve type-stability wherever possible.
For example, init = 0.0 is better than init = 0 at least on papier, because the sum will end up being a Float64 and not an Int, so it’s better to initialize it that way. See also Performance Tips · The Julia Language