I want to use enums as integers, especially for array indexing.
 
So I started to implement an IntEnum type, so I could do something like the 
following:
 
julia> @intenum Animal pig dog cat
 
julia> pig
pig=1
 
julia> dog
dog=2
 
julia> A = zeros(length(Animal))
3-element Array{Float64,1}:
0.0
0.0
0.0
 
julia> A[dog] = 10.5
10.5
 
julia> A
3-element Array{Float64,1}:
 0.0
10.5
 0.0
 
s = 0.0
for i in eachindex(Animal)
   s += A[i]
end
 
 
 
Then I realized my code was similar to the existing Enum type in Base with 
a few exceptions/additions:

   - abstract IntEnum is a subtype of Integer (this allows use with array 
   indexing)
   - default enumerations start at 1 rather 0 (so defaults work with array 
   indexing)
   - introduced length(), eachindex() functions
   - plus some other cosmetic changes (e.g. show() prints both label and 
   associated integer (pig=1) 

 
Q1. Are there any problems with my type inheriting from Integer? (actually, 
super(Int) 
== Signed)
 
 
Q2. I implemented my type and conversion to/from Integers as follows 
(simplified):
 
immutable $enum <: IntEnum
   i::Int
end
 
Base.convert{E<:IntEnum}(::Type{E}, x::Integer) = T(Int(x))
Base.convert{I<:Integer}(::Type{I}, x::IntEnum) = I(x.i) 
 
compared to Enum implementation (also simplified):
 
bitstype <Base.@__doc__(bitstype> 32 $enum <: Enum
 
Base.convert(::Type{$enum}, x::Integer) = Intrinsics.box($enum, convert(
Int32, x))
Base.convert{T<:Integer}(::Type{T}, x::Enum) = convert(T, Intrinsics.box(
Int32, x))
 
a) Are bitstypes faster than immutable composite types? Are there other 
advantages/disadvantages?
 
b) What is the difference between boxing Intrinsics.Box and using 
reinterpret?
 
 
Q3. I can't help but feel this is a really stupid question, but here goes 
anyway ...
 
Compare these implementations of defining a function to return a constant / 
immutable
 
global const xxx = (a,b,c,d)
names1(::Type{Y}) = xxx

 
names2(::Type{Y}) = (a,b,c,d)

 
Is names2 as efficient as names1?, in the sense that it doesn't allocate a 
new tuple on each call?
If so, is this because a tuple is immutable?
So if it returned say an array instead, it would allocate a new array each 
call (even if that array was intended to be const)?

Reply via email to