0
votes

In my code I use Julia's prod() function to do a product over the elements of a list. However, sometimes that list is empty, in which case I want prod(myList) to just return 0 (or any fixed number like 1). I tried searching online, but the only things I could find were for iterators or stuff like that.

I'm using Julia version 1.5.2.

4
What does eltype(MyList) give when that list is empty? As mentioned in the comments, I think prod is the right function to use without modification and that the real issue may be how you create that empty list. - Benoit Pasquier

4 Answers

4
votes

Would a simple ternary operator work for your case?

isempty(my_list) ? 0 : prod(my_list)
3
votes

What you want is incorrect/unconventional. The product of the elements of an empty sequence should be 1, because that is the multiplicative identity element.

1
votes

"Any fixed number" is easy:

reduce(*, ls; init=1)

But this does not work well with zero, since that is an annihilator and sends the whole product to zero:

julia> ls = [1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> reduce(*, ls; init=0)
0

Now, returning 1 and then checking for that works if you only have integers. It doesn't as soon as you have a product over rationals, since then the resulting 1 could also stem from x * (1/x).

0
votes
julia> zeroprod(x) = isempty(x) ? zero(eltype(x)) : prod(x)
zeroprod (generic function with 1 method)