Reversing order of `prod(itr)`

Is there a way to make the product built by prod(itr) from right to left instead from left to right? So I want

julia> prod("$i" for i in [1,2,3]) == "123"

instead of

julia> prod("$i" for i in [1,2,3]) == "321"

?

Note that in my case using Iterators.reverse does not work, because I get MethodError: no method matching iterate(::Base.Iterators.Reverse{Dict{Int64,String}}

What collection are you actually trying to prod over? reverse on the input works fine for me:

julia> prod("$i" for i in Iterators.reverse([1,2,3]))
"321"

as does regular reverse:

julia> reverse(prod("$i" for i in [1,2,3]))
"321"

If you are using a dictionary, the iteration order is undefined and may change from release to release. So I think you need a different data structure if you want a specific order.

2 Likes

I guess I am out of luck then and need to do

str = ""
for i in [1,2,3]
    str = str * "$i"
end

because my iterator (a dict) happens to be ordered the way I want it. And since it is only for string representation this order is not a must, but more convenient to read.

Over pair(Dict(Int => String)) and because of the way I create it, it usually happens to be iterated over in the “correct” order.

Well you can reverse(collect(mydict)) if efficiency is not a concern and if reverse unspecified order looks better than unspecified order

You realize that you can’t rely on this? The ordering of a Dict may change unpredictably as you add elements, or if you update Julia to a new version. Don’t use Dict if you want a specific iteration order; use something else like the OrderedDict type in the OrderedCollections.jl package.

Don’t accumulate strings this way — every iteration of your loop allocates and copies into a new string. See this discussion: Accumulating strings dynamically - #3 by stevengj

6 Likes

Thanks for pointing out the thread about string accumulation! About the order: As @FPGro said the reverse, unspecified order looks better than the unspecified order, but the exact order is no hard constraint. Just a “nice to have”