Julia, for loop iterator increase to zero

Viewed 141

I have a nice function that sums a group of random numbers generated with this function.

sum(round(Int8, floor(
        rand(TruncatedNormal(var1, var2, var3, var4))))
                     for _ in 1:var5)

Most of the time it works fine, var5, the iterator for the for loop is calculated earlier in a function, and can legitimately be a zero. Therefore iterating by increasing from 1 to 0 doesn't work and throws an error. Is there a clean "check" in Julia that will simply produce a result of 0 for the whole function, or do I need to go back and enclose this function in an if statement to check the value of var5 prior to running it, and if var5<=0, produce an alternate result (0)? Thx. J

2 Answers

When you do sum(rand(Int8) for _ in 1:0) you get the error:

julia> sum(rand(Int8) for x in 1:0)
ERROR: ArgumentError: reducing over an empty collection is not allowed
Stacktrace:
 [1] _empty_reduce_error() at ./reduce.jl:299
 [2] mapreduce_empty(::Function, ::Base.BottomRF{typeof(Base.add_sum)}, ::Type{T} where T) at ./reduce.jl:342
 [3] reduce_empty(::Base.MappingRF{var"#9#10",Base.BottomRF{typeof(Base.add_sum)}}, ::Type{Int64}) at ./reduce.jl:329
 [4] reduce_empty_iter at ./reduce.jl:355 [inlined]
 [5] reduce_empty_iter at ./reduce.jl:354 [inlined]
 [6] foldl_impl at ./reduce.jl:49 [inlined]
 [7] mapfoldl_impl at ./reduce.jl:44 [inlined]
 [8] #mapfoldl#204 at ./reduce.jl:160 [inlined]
 [9] mapfoldl at ./reduce.jl:160 [inlined]
 [10] #mapreduce#208 at ./reduce.jl:287 [inlined]
 [11] mapreduce at ./reduce.jl:287 [inlined]
 [12] sum at ./reduce.jl:494 [inlined]
 [13] sum(::Base.Generator{UnitRange{Int64},var"#9#10"}) at ./reduce.jl:511
 [14] top-level scope at REPL[6]:1

One very simple workaround is to collect the random numbers into an array first — or simply use a comprehension instead of a generator:

julia> sum([rand(Int8) for x in 1:0])
0

You could also use the ternary expression as linked above to simply avoid the problem altogether:

julia> var5 = 0
0

julia> var5 < 1 ? 0 : sum(rand(Int8) for x in 1:var5)
0

julia> var5 = 2
2

julia> var5 < 1 ? 0 : sum(rand(Int8) for x in 1:var5)
49

For cases where you need to catch the case of summing over an empty collection, I prefer an explicit reduce with an init value:

julia> reduce(+, (rand(Int8) for x in 1:0), init=Int8(0))
0
Related