julia> @btime (n -> [iseven(k) ? 1 : (-1) for k in 1:n])(500);
890.571 ns (1 allocation: 4.06 KiB)
julia> @btime (n -> [(-1)^k for k in 1:n])(500);
6.170 μs (1 allocation: 4.06 KiB)
It would be great if the latter could be transformed into the former through constant propagation. I wonder if there are edge cases where this won’t hold?
k is not a constant here so it’s something other than constant propagation. I’m not sure where a -1 branch should be put if that’s the way to do it. It also occurs to me, the branch shouldn’t just be for -1, right; any negative value to the power of a k::Integer can check k for evenness to calculate the sign and compute the absolute value to that power, and so (-1)^k should boil down to 1^k with its own 1 branch.