Book Image

Mastering Julia

Book Image

Mastering Julia

Overview of this book

Table of Contents (17 chapters)
Mastering Julia
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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