Get the enumerate type components from the string counterpart

#1

This is a simple task. I tried the following and it did not work.

julia> @enum Fruit apple=0 pear=1 banana=2 
julia> Fruit("apple")
ERROR: MethodError: no method matching Fruit(::String)
Closest candidates are:
  Fruit(::Integer) at Enums.jl:134
Stacktrace:
 [1] top-level scope at none:0
#2

Is there a reason to avoid the enum’s names?

julia>  @enum Fruit apple=0 pear=1

julia> apple
apple::Fruit = 0

julia> pear
pear::Fruit = 1
#3

I have a string, say, “banana”, I’d like to change it back to the corresponding enumerate type…

#4

without error checking

julia> function fruit(s::String)
          [apple, pear][s .== ["apple", "pear"]][1]
       end
fruit (generic function with 1 method)

julia> fruit("pear")
pear::Fruit = 1

or

function fruit(s::String)
      Fruit( (0:1)[s .== ["apple", "pear"]][1] )
end
1 Like
#5

Good. Are there default functions that I can use directly? By the way, what is s .==?

#6

s .== [a, b] is [s === a, s === b]
s .= [a, b] is [s == a, s == b]

Default functions for what purpose?

#7

for transfer a string to the enumerate type counterpart

#8

not entirely

julia> instances(Fruit)
(apple, pear)

julia> string.(instances(Fruit))
("apple", "pear")
#9

what you did above is transferring the enumerate to string counterpart.

#10

you can do this

const fruits = instances(Fruit)
const fruitvalues = Int32.(fruits)
const fruitstrings = string.(fruits)
fruit(s::String) = Fruit(fruitvalues[[(s .== fruitstrings)...]][1])

fruit("apple")
apple::Fruit == 0
3 Likes