1

Please explain the following example.

julia> string_foo = "foo"
"foo"

julia> eval(string_foo)
"foo"

julia> eval(:string_foo)
"foo"

julia> a_dict = Dict(:string_foo => 1, "string_foo" => 2,string_foo => 3)
Dict{Any,Int64} with 3 entries:
  "string_foo" => 2
  :string_foo  => 1
  "foo"        => 3

Not so surprising results:

julia> a[string_foo]
3

julia> a["string_foo"]
2

julia> a[:string_foo]
1

More not so surprising results:

julia> a[eval(string_foo)]
3

julia> a[eval("string_foo")]
2

Now please explain this one!

julia> a[eval(:string_foo)]
3

My hesitant conclusion is that when a variable (foo) the same as symbol (:foo) is defined, then one can use it as a key (:foo) or as a value (eval(:foo))

This means that I could do the following before defining any variables at all:

julia> list_template = [:el1, :el2, :el3]
3-element Array{Symbol,1}:
 :el1
 :el2
 :el3

julia> el1 = 1; el2 = 2; el3 = 3;

julia> eval(list_template)
3-element Array{Symbol,1}:
 :el1
 :el2
 :el3

julia> eval.(list_template)
3-element Array{Int64,1}:
 1
 2
 3

julia> el1 = "one"; el2 = "two"; el3 = "three";

julia> eval(list_template)
3-element Array{Symbol,1}:
 :el1
 :el2
 :el3

julia> eval.(list_template)
3-element Array{String,1}:
 "one"  
 "two"  
 "three"

That seems like it could be useful in some cases. What other uses do Julia Symbols have?

dnk8n
  • 675
  • 8
  • 21
  • 5
    [metaprogramming](https://docs.julialang.org/en/latest/manual/metaprogramming/) – Gnimuc Mar 08 '19 at 09:41
  • https://stackoverflow.com/a/23482257/2372611 – hckr Mar 08 '19 at 18:24
  • I read this multiple times. It explains what a symbol is but not about their use cases. The examples provided leave a lot to the imagination. I don't have a robust enough knowledge of the language to make connections required. So here I am asking, how are Symbols useful. I.e. what are their use-cases. I am looking for real common and novel use-cases. – dnk8n Mar 09 '19 at 09:55
  • 1
    I did not see the question as a duplicate or flagged it as one. That's why I shared a link to *an answer* thinking that you and other people might find the information in it helpful for your question. It also gives a reason why `DataFrames.jl` uses symbols over strings. Although both questions ask the same thing (i.e. symbols vs string), the context is a bit different. – hckr Mar 09 '19 at 11:36
  • TLDR answer: Julia is [homoiconic](https://en.wikipedia.org/wiki/Homoiconicity) and you need `Symbol`s to represent and manipulate the AST (abstract syntax tree) – Przemyslaw Szufel Mar 10 '19 at 00:54
  • I know @hckr, sorry that last message was directed at matt-b – dnk8n Mar 10 '19 at 13:33

0 Answers0