O'Reilly logo

Mastering Julia by Malcolm Sherrington

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required