How is it that the generic function manages to create an invalid Probability variable in the code below? Is this a compiler bug?
import math
type Probability = range[0.0..1.0]
proc probSum(ps: openArray[Probability]): Probability =
for p in items(ps):
result += p
let ps = @[Probability 0.5, 0.5, 0.5]
# The following line should raise an error, but doesn't
echo "Using math sum: ", sum(ps), " typeof: ", typeof(sum(ps))
# This line raises and error
# echo "Using probSum: ", probSum(ps), " typeof: ", typeof(probSum(ps))
whats strange is that if you just copy the function from math to current module it will raise properly.
type Probability = range[0.0..1.0]
proc sum*[T](x: openArray[T]): T {.noSideEffect.} =
## Computes the sum of the elements in ``x``.
##
## If ``x`` is empty, 0 is returned.
##
## See also:
## * `prod proc <#prod,openArray[T]>`_
## * `cumsum proc <#cumsum,openArray[T]>`_
## * `cumsummed proc <#cumsummed,openArray[T]>`_
runnableExamples:
doAssert sum([1, 2, 3, 4]) == 10
doAssert sum([-1.5, 2.7, -0.1]) == 1.1
for i in items(x): result = result + i
let ps = @[Probability 0.5, 0.5, 0.5]
# The following line raises properly
echo "Using math sum: ", sum(ps), " typeof: ", typeof(sum(ps))
ah, its not strange at all, math module just explicitly disables all checks
{.push checks: off, line_dir: off, stack_trace: off.}
Thanks -- I wasn't aware of .push checks: off or even that run-time type checking could be completely disabled!
This seems like it would be important to document in the intro section of the math module docs. I'll file an issue on GitHub.