2

Question: Can I divide a symbol into two symbols based on a letter or symbol?

Example: For example, let's say I have :symbol1_symbol2, and I want to split it on the _ into :symbol1 and :symbol2. Is this possible?

Motivation: A fairly common recommendation in Julia is to use Symbol in place of String or ASCIIString as it is more efficient for many operations. So I'm interested in situations where this might break down because there is no analogue for Symbol for an operation that we might typically perform on ASCIIString, e.g. anything to do with regular expressions.

Colin T Bowers
  • 18,106
  • 8
  • 61
  • 89

1 Answers1

3

No you can't manipulate symbols. They are not a composite type (in logic, though they maybe in implement). They are one thing. Much like an integer is one thing, or a boolean is one thing. You can't manipulate the parts of it.

As I understand, it the reason they are fast is because thay are "one thing".

Symbols are not strings. Symbols are the representation of a parsed token. They exist for working with macros etc.

They are useful for other things. Though one fo there most common alterate uses in 0.3 was as a standin for enumerations. Now that Enum is in 0.4, that use will decline. They are still logically good for dictionary keys etc.

--

If for some reason you must. Eg for interop with a 3rd party library, or for some kind of dynamic dispatch:

You can convert it to a String, with string(:abc), (There is not currently a convert), and back with Symbol("abc").

so

function symsplit(s_s::Symbol)
    combined_string_from=string(s_s)
    strings= split(combined_string_from, '_')
    map(Symbol,strings)
end


@show  symsplit(:a)
@show  symsplit(:a_b)
@show symsplit(:a_b_c);

but please don't.

You can find all the methods that operate on symbols by calling methodswith(Symbol) (though most just use the symbol as a marker/enum)


See also:

What is a "symbol" in Julia?

Community
  • 1
  • 1
Frames Catherine White
  • 27,368
  • 21
  • 87
  • 137