Enumerations (revisited)

One problem with our vehicle type is that the fuel is defined as a string, whereas it would be better to restrict the choice to set of values. Previously, we discussed a macro that provides one approach to enumerations. In the absence of a preferred definition in Julia, various developers have adopted different strategies and I'll provide our own here.

First, we will use a vector of type {Any} to hold the enumerated values. This could be consts using integers or strings, but I'll restrict it to a list of symbols and create the vnum.jl file to hold the following:

typealias VecAny Array{Any,1}
function vnum(syms::Symbol...)
  A = {}
  for v in syms
    push!(A,v)
  end
  A
end
function vidx(A::VecAny, a::Symbol)
 for (i, v) in enumerate(A) ...

Get Mastering Julia now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.