Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Mastering Julia

You're reading from  Mastering Julia

Product type Book
Published in Jul 2015
Publisher
ISBN-13 9781783553310
Pages 410 pages
Edition 1st Edition
Languages

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)
    if v == a then
      return (i - 1)
    end
    nothing
  end
end
vin(A::VecAny, a::Symbol) = (vidx(A,a) >= 0 ? true : false)

vnum is created by pushing a variable list of symbols onto an empty Any vector. Additionally, there...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}