BlockEnums is like the built-in Enums. The main differences are
- Enumerated types are mutable in the sense that instances may be added after the type is created.
- The type may be optionally enclosed in a module (a namespace).
- The enumeration may be partitioned into blocks of values. For example
@addinblock A 2 x
would add the instancex
to typeA
in the second block of indices.
These are supported by keyword arguments blocklength
, mod
, numblocks
.
There is also a keyword compactshow
that causes the integer associated with the enum value to be
omitted when displaying.
It came to my attention at JuliaCon2023 that JuliaSyntax.jl includes a type Kind
that has similarities
with BlockEnums.jl
.
- They are both like
Base.Enums
in that they are primitive types:primitive type Kind 16 end
- Intervals of the integer values have semantic significance. A difference is that the "blocks" in
Kind
are smaller and fixed.
The motivation for Kind
is essentially the same as for BlockEnums
:
Kind
is a type tag for specifying the type of tokens and interior nodes of a syntax tree. Abstractly, this tag is used to define our own sum types for syntax tree nodes. We do this explicitly outside the Julia type system because (a) Julia doesn't have sum types and (b) we want concrete data structures which are unityped from the Julia compiler's point of view, for efficiency.
And here
# The implementation of Kind here is basically similar to @enum. However we use
# the K_str macro to self-name these kinds with their literal representation,
# rather than needing to invent a new name for each.
julia> using BlockEnums
julia> @blockenum Fruit apple banana
julia> Fruit
BlockEnum Fruit:
apple = 0
banana = 1
julia> @add Fruit pear
pear::Fruit = 2
julia> Fruit
BlockEnum Fruit:
apple = 0
pear = 2
banana = 1
Some block features
julia> using BlockEnums
julia> @blockenum (Myenum, mod=MyenumMod, blocklength=100, numblocks=10, compactshow=false)
julia> @addinblock Myenum 1 a b c
c::Myenum = 3
julia> @addinblock Myenum 3 x y z
z::Myenum = 203
julia> BlockEnums.blockindex(MyenumMod.y)
3
Methods for the following functions in Base
are defined and follow the established semantics.
cconvert
write
, converts to the underlying bitstype before writing.read
, reads a value from the bitstype and converts to theBlockEnum
isless
Symbol
length
typemin
,typemax
These are the min and max of values with names bound to them.instances
print
BlockEnums passes JET.jl and Aqua.jl tests.
See EnumsX and other packages listed at the bottom of that page.