Using `Enum`s as indices

I’m using enum’s for some purposes. In particular for indexing arrays. It works fine, except for some types of broadcasting:

a = [zeros(10) for _ in 1:4];
b = [zeros(10) for _ in 1:4];
@enum Count one=1 two three four

Base.to_index(c::Count) = Int(c)

a[1] .= b[1]
a[1] .= b[one]
a[one] .= b[one]

The last broadcast assignment fails with

ERROR: DimensionMismatch: cannot broadcast array to have fewer non-singleton dimensions

I can work around with

aone = a[one]
aone .= b[one]

What magic does it take to make this work without the workaround?

You might like GitHub - mcabbott/AxisKeys.jl: 🎹 for non-numeric keys.

That sounds like an even more elaborate workaround.

One way to make it work is:

Base.dotview(A::AbstractArray, c::Count) = Base.dotview(A, Int(c))

but I suspect that this is not a good practice. I leave it here in case you really need it, but I’m sure there is a more reasonable way to achieve what you want.

1 Like