Convert String to DataType

I have a file that contains a List of what “Algo” I should run
Then Julia should read it and Create an instance of the correct “Algo” object:

abstract type OptimizationAlgo end
struct Linear <: OptimizationAlgo end
struct Quad <: OptimizationAlgo end
struct ThirdOrder <: OptimizationAlgo end

algo_str = readline() # Let's say I type in "Linear"

# Convert algo_str to the correct algo struct
# How to do it??

But how to efficiently do so?

The only way I could think of:

@eval $(Symbol(algo_str))

Is there a way Without Using any Macro?

1 Like

i can’t think of another solution of that other that a long function with a lot of ifs, maybe that is the correct approach, because the algorithm is not known a priori (before reading the file)

Is there a way Without Using any Macro?

If the number of algorithms is limited you can use a dictionary as a mapping from string to object.

3 Likes

You can short circuit equality for string such as


julia> algo_str = readline()
Linear
"Linear"

julia> algo_str == "Linear" && Linear()
Linear()

or you can construct a dictionary from strings to algos if the list of algos is long

julia> b = Dict("Linear"=>Linear())
Dict{String,Linear} with 1 entry:
  "Linear" => Linear()

julia> b[algo_str]
Linear()

But second one has the problem of type-stability if more algos is mixed in dictionary.

If you don’t want to use a macro, getproperty(Main, Symbol(algo_str)) does the job.

3 Likes

Thank you! problem solved.