M.E.
M.E.

Reputation: 5527

Is there any #define equivalent in Julia?

I am implementing some basic state machine which several states in Julia.

In C I would trace the current state using something similar to:

#define STOP 1
#define START 2
#define ERROR 3

And then use the friendly constants in comparisons, etc.

if(state == STOP) {
    printf("Stop state.\n");
}

Is there something equivalent to #define in Julia?

Upvotes: 3

Views: 247

Answers (2)

Cameron Bieganek
Cameron Bieganek

Reputation: 7704

You can use an enum. Enums are defined using the @enum macro:

@enum State STOP START ERROR

This creates three constants, STOP, START, and ERROR, all of type State. This means you can dispatch functions on the type of an enum:

import Base.println
function println(s::State)
    if s == STOP
        println("Stop state.")
    elseif s == START
        println("Start state.")
    else
        println("Error state.")
    end
end
julia> s = STOP

julia> println(s)
Stop state.

Enums can be converted to integer values:

julia> Int.([STOP, START, ERROR])
3-element Array{Int64,1}:
 0
 1
 2

As you can see, the default integer values for the sequence of enum states starts at 0. However, you can choose to explicitly set the integer values for the enums when you use the @enum macro:

julia> @enum Heat LOW=1 MEDIUM=2 HIGH=3

julia> Int.([LOW, MEDIUM, HIGH])
3-element Array{Int64,1}:
 1
 2
 3

Note that when creating a switch, like in the println definition above, you can be confident that STOP, START, and ERROR are the only possible values of a State object. This can be demonstrated by explicitly constructing State objects:

julia> State(0), State(1), State(2)
(STOP::State = 0, START::State = 1, ERROR::State = 2)

julia> State(3)
ERROR: ArgumentError: invalid value for Enum State: 3
Stacktrace:
 [1] enum_argument_error(::Symbol, ::Int64) at ./Enums.jl:34
 [2] State(::Int64) at ./Enums.jl:139
 [3] top-level scope at none:0

Upvotes: 8

Jeffrey Sarnoff
Jeffrey Sarnoff

Reputation: 1757

If you really want something as close a possible to #define <Symbol> <Integer> use const:

const STOP  = 1
const START = 2
const ERROR = 3

Upvotes: 6

Related Questions