Symbol (programming): Difference between revisions

Content deleted Content added
Undid revision 924668795 by 117.211.160.77 (talk): ?
Tags: Mobile edit Mobile web edit Advanced mobile edit
 
(30 intermediate revisions by 24 users not shown)
Line 1:
{{generalize|date=October 2023}}{{Short description|Datatype in programming}}
{{distinguish|Symbol (computing)}}
A '''symbol''' in [[computer programming]] is a [[Primitive data type|primitive]] [[data type]] whose [[Instance (computer science)|instances]] have a unique human-readable form. Symbols can be used as [[Identifier (computer languages)|identifier]]s. In some [[programming languageslanguage]]s, they are called '''atoms'''.<ref name=pickaxe>{{cite book |lastlast1=HuntThomas |firstfirst1=Dave |author1-link=Dave Thomas ;(programmer) |last2=Fowler |first2=Chad Fowler|last3=Hunt ;|first3=Andy |author3-link=Andy Hunt (author) |year=2001 |title=Programming Ruby the pragmatic programmers' guide ; [includes Ruby 1.8]|year=2001 |publisher=The Pragmatic Bookshelf |___location=Raleigh, NCNorth Carolina |isbn=978-0-9745140-5-5 |url=https://archive.org/detailsdetail/programmingrubyp00thom |edition=2. ed.2nd, 10. print. |url-access=registration}}</ref> Uniqueness is enforced by holding them in a [[symbol table]]. The most common use of symbols by programmers is forto performingperform language [[reflectionReflective (programming) | reflection]] (particularly for [[callbackCallback (computer programming)|callbacks]]), and the most common indirectly is their use to create object [[linkageLinkage (software)|linkages]].
 
In the most trivial [[implementation]], they are essentially named [[integer]]s; (e.g., the [[enumerated type]] in [[C (programming language)|C]] language.
 
==Support==
Line 11:
! language || type name(s) || example literal(s)
|-
| [[ANSI]] [[Common Lisp]] || symbol, keyword || <ttcode>symbol</ttcode>, <ttcode>:keyword</ttcode>
|-
| [[Clojure]] || symbol,<ref>[http://clojure.org/data_structures#Data%20Structures-Symbols Symbols] on the page on Data Structures</ref> keyword<ref>[http://clojure.org/data_structures#Data%20Structures-Keywords Keywords] on the page on Data Structures</ref> || <ttcode>'symbol</ttcode>, <ttcode>:keyword</ttcode>
|-
| [[Dart (programming language)|Dart]] || Symbol<ref>{{cite web |title=A tour of the Dart language {{pipe}} Symbols |url=https://dart.dev/guides/language/language-tour#symbols |website=Dart programming language |access-date=17 January 2021}}</ref> || <code>#sym</code>
| [[Elixir (programming language)|Elixir]] || atom, symbol || <tt>:sym</tt>
|-
| [[ErlangElixir (programming language)|ErlangElixir]] || atom, symbol || <tt>sym</tt> or <ttcode>':sym'</ttcode>
|-
| [[JuliaErlang (programming language)|JuliaErlang]] || Symbolatom || <ttcode>:sym</ttcode> or <code>'sym'</code>
|-
| [[Objective-CJavaScript]] (ES6 and later) || SELSymbol || <ttcode>@selectorSymbol("sym");</ttcode>
|-
| [[PICAXE]]Julia (programming [[BASIClanguage)|Julia]] || symbolSymbol || <ttcode> symbol let name = variable :sym</ttcode>
|-
| [[PrologK (programming language)|PrologK]] || atom, symbol || <tt>sym</tt> or <tt>'`sym'</tt>
|-
| [[Ruby (programming language)|RubyObjective-C]] || SymbolSEL || <ttcode>:@selector(sym)</tt> or <tt>:'sym'</ttcode>
|-
| [[Scala (programmingPICAXE]] language)|Scala[[BASIC]] || scala.Symbolsymbol || <ttcode>' symbol let name = variable </ttcode>
|-
| [[Scheme (programming language)|SchemePostScript]] || symbolname || <ttcode>/sym</code> or <code>sym</ttcode>
|-
| [[SmalltalkProlog]] || Symbolatom, symbol || <ttcode>#sym</ttcode> or <ttcode>#'sym'</ttcode>
|-
| [[Ruby (programming language)|Ruby]] || Symbol || <code>:sym</code> or <code>:'sym'</code>
| [[SML/NJ]] || Atom.atom ||
|-
| [[JavaScript]]Scala (ES6programming and laterlanguage)|Scala]] || scala.Symbol || <ttcode>Symbol("sym");'symbol</ttcode>
|-
| [[ElixirScheme (programming language)|ElixirScheme]] || atom, symbol || <ttcode>:symsymbol</ttcode>
| [[Wolfram Language]] || Symbol || <tt>Symbol["sym"]</tt> or <tt>sym</tt>
|-
| [[Smalltalk]] || Symbol || <code>#sym</code> or <code>#'sym'</code>
|[[K (programming language)]]
|-
|symbol
| [[SML/NJ]] || Atom.atom ||
|`sym
|-
| [[Wolfram Language]] || Symbol || <ttcode>Symbol["sym"]</ttcode> or <ttcode>sym</ttcode>
|}
 
===Julia===
Symbols in [[Julia (programming language)|Julia]] are [[String interning|interned strings]] used to represent identifiers in parsed Julia code([[Abstract syntax tree|ASTs]]) and as names or labels to identify entities (for example as keys in a dictionary).<ref>{{cite web |title=Julia Core.Symbol |url=https://docs.julialang.org/en/v1/base/base/#Core.Symbol |website=Julia Documentation |access-date=31 May 2022}}</ref>
 
===Lisp===
A symbol in [[Lisp (programming language)|Lisp]] is unique in a [[namespace]] (or ''package'' in [[Common Lisp]]). Symbols can be tested for equality with the function EQ. Lisp programs can generate new symbols at runtime. When Lisp reads data that contains textual represented symbols, existing symbols are referenced. If a symbol is unknown, the Lisp reader creates a new symbol.
 
In Common Lisp, symbols have the following attributes: a name, a value, a function, a list of properties and a package.<ref>[{{Cite web|url=http://www.lispworks.com/documentation/HyperSpec/Body/t_symbol.htm|title=CLHS: CommonSystem LispClass HyperSpec, system class Symbol]SYMBOL|website=www.lispworks.com}}</ref>
 
In Common Lisp it is also possible that a symbol is not interned in a package. Such symbols can be printed, but when read back, a new symbol needs to be created. Since it is not *''interned*'', the original symbol can't not be retrieved from a package.
 
In Common Lisp symbols may use any characters, including whitespace, such as spaces and newlines. If a symbol contains a whitespace character, it needs to be written as |this is a symbol|. Symbols can be used as identifiers for any kind of named programming constructs: variables, functions, macros, classes, types, goto tags and more.
Symbols can be interned in a package.<ref>[{{Cite web|url=http://www.lispworks.com/documentation/HyperSpec/Body/t_pkg.htm#package|title=CLHS: CommonSystem LispClass HyperSpec, system class Package]PACKAGE|website=www.lispworks.com}}</ref> Keyword symbols are self-evaluating,<ref>[[Peter Norvig]]: ''Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp'', Morgan Kaufmann, 1991, {{ISBN|1-55860-191-0}}, [http://norvig.com/paip.html Web]</ref> and interned in the package named KEYWORD.
 
====Examples====
The following is a simple external representation of a [[Common Lisp]] symbol:
<sourcesyntaxhighlight lang="lisp">
this-is-a-symbol
</syntaxhighlight>
</source>
 
Symbols can contain whitespace (and all other characters):
<sourcesyntaxhighlight lang="lisp">
|This is a symbol with whitespace|
</syntaxhighlight>
</source>
 
In Common Lisp symbols with a leading colon in their printed representations are [[Keyword (computer programming)|keyword symbols]]. These are interned in the keyword package.
<sourcesyntaxhighlight lang="lisp">
:keyword-symbol
</syntaxhighlight>
</source>
 
A printed representation of a symbol may include a package name. Two colons are written between the name of the package and the name of the symbol.
<sourcesyntaxhighlight lang="lisp">
package-name::symbol-name
</syntaxhighlight>
</source>
 
Packages can export symbols. Then only one colon is written between the name of the package and the name of the symbol.
<sourcesyntaxhighlight lang="lisp">
package:exported-symbol
</syntaxhighlight>
</source>
 
Symbols, which are not interned in a package, can also be created and have a notation:
<sourcesyntaxhighlight lang="lisp">
#:uninterned-symbol
</syntaxhighlight>
</source>
 
===PostScript===
In [[PostScript]], references to ''name'' objects can be either ''literal'' or ''executable'', influencing the behaviour of the interpreter when encountering them. The <code>cvx</code> and <code>cvl</code> operators can be used to convert between the two forms. When names are constructed from strings by means of the <code>cvn</code> operator, the set of allowed characters is unrestricted.
 
===Prolog===
In [[Prolog (programming language)|Prolog]], symbols (or atoms) are the primarymain primitive data types, similar to numbers.<ref name=Bratko2001>{{Cite book | last1 last= Bratko | first1 first= Ivan |year=2001 |title = Prolog programming for artificial intelligence | year = 2001 | publisher = Addison Wesley | ___location = Harlow, England ; New York | isbn = 978-0-201-40375-6 | pages = }}</ref> The exact notation may differ in different Prolog's dialects. However, it is always quite simple (no quotations or special beginning characters are necessary).
 
Contrary to many other languages, it is possible to give symbols somea ''meaning'' by creating some Prolog's facts and/or rules.
 
====Examples====
The following example demonstrates two facts (describing what ''father'' is) and one rule (describing the ''meaning'' of ''sibling''). These three sentences use symbols (father, zeus, hermes, perseus and sibling) and some abstract variables (X, Y and Z). The ''mother'' relationship has beenis omitted for clarity.
<sourcesyntaxhighlight lang="prolog">
father(zeus, hermes).
father(zeus, perseus).
 
sibling(X, Y) :- father(Z, X), father(Z, Y).
</syntaxhighlight>
</source>
 
===Ruby===
In [[Ruby (programming language)|Ruby]], symbols can be created with a literal form, or by converting a string.<ref name=pickaxe />
They can be used as an identifier or an interned string.<ref name="rubysymbol">{{cite web |last=Kidd |first=Eric |date=20 January 2007 |title=13 Ways of Looking at a Ruby Symbol |url=http://www.randomhacks.net/articles/2007/01/20/13-ways-of-looking-at-a-ruby-symbol#9 |work=Random Hacks |accessdateaccess-date=10 July 2011}}</ref> Two symbols with the same contents will always refer to the same object.<ref>{{Cite web | url=httphttps://wwwdocs.ruby-doclang.org/docsen/ProgrammingRubymaster/html/languageSymbol.html#UI | title=Programming Ruby: The Pragmatic Programmer's Guide}}</ref>
It is considered a [[best practice]] to use symbols as keys to an [[associative array]] in Ruby.<ref name=rubysymbol /><ref name="wrongreason">{{cite web|title=Using Symbols for the Wrong Reason|url=http://microjet.ath.cx/WebWiki/2005.12.27_UsingSymbolsForTheWrongReason.html|work=Gnomic Notes}}</ref>
 
====Examples====
The following is a simple example of a symbol literal in Ruby:<ref name=pickaxe />
<sourcesyntaxhighlight lang=ruby>
my_symbol = :a
my_symbol = :"an identifier"
</syntaxhighlight>
</source>
Strings can be coerced into symbols, vice versa:
<sourcesyntaxhighlight lang=irb>
irb(main):001:0> my_symbol = "Hello, world!".intern
=> :"Hello, world!"
Line 120 ⟶ 128:
irb(main):003:0> my_string = :hello.to_s
=> "hello"
</syntaxhighlight>
</source>
Symbols are objects of the <code>Symbol</code> class in Ruby:<ref name="rdocsymbol">{{cite web|title=Symbol|url=httphttps://wwwdocs.ruby-doclang.org/coreen/classesmaster/Symbol.html|work=Ruby Documentation|accessdateaccess-date=10 July 2011}}</ref>
<sourcesyntaxhighlight lang=irb>
irb(main):004:0> my_symbol = :hello_world
=> :hello_world
Line 129 ⟶ 137:
irb(main):006:0> my_symbol.class
=> Symbol
</syntaxhighlight>
</source>
Symbols are commonly used to dynamically send messages to (call methods on) objects:
<sourcesyntaxhighlight lang=irb>
irb(main):007:0> "aoboc".split("o")
=> ["a", "b", "c"]
irb(main):008:0> "aoboc".send(:split, "o") # same result
=> ["a", "b", "c"]
</syntaxhighlight>
</source>
Symbols as keys of an associative array:
<sourcesyntaxhighlight lang=irb>
irb(main):009:0> my_hash = { a: "apple", b: "banana" }
=> {:a=>"apple", :b=>"banana"}
Line 145 ⟶ 153:
irb(main):011:0> my_hash[:b]
=> "banana"
</syntaxhighlight>
</source>
 
===Smalltalk===
In [[Smalltalk]], symbols can be created with a literal form, or by converting a string. They can be used as an identifier or an interned string. Two symbols with the same contents will always refer to the same object.<ref>http://wiki.squeak.org/squeak/uploads/172/standard_v1_9-indexed.pdf ANSI Smalltalk standard.</ref> In most Smalltalk implementations, selectors (method names) are implemented as symbols.
They can be used as an identifier or an interned string. Two symbols with the same contents will always refer to the same object.<ref>http://wiki.squeak.org/squeak/uploads/172/standard_v1_9-indexed.pdf ANSI Smalltalk standard.</ref> In most Smalltalk implementations, selectors (method names) are implemented as symbols.
 
====Examples====
The following is a simple example of a symbol literal in Smalltalk:
<sourcesyntaxhighlight lang=smalltalk>
my_symbol := #'an identifier' " Symbol literal "
my_symbol := #a " Technically, this is a selector literal. In most implementations, "
" selectors are symbols, so this is also a symbol literal "
</syntaxhighlight>
</source>
Strings can be coerced into symbols, vice versa:
<sourcesyntaxhighlight lang=smalltalk>
my_symbol := 'Hello, world!' asSymbol " => #'Hello, world!' "
my_string := #hello: asString " => 'hello:' "
</syntaxhighlight>
</source>
Symbols conform to the <code>symbol</code> protocol, and their class is called <code>Symbol</code> in most implementations:
<sourcesyntaxhighlight lang=smalltalk>
my_symbol := #hello_world
my_symbol class " => Symbol "
</syntaxhighlight>
</source>
Symbols are commonly used to dynamically send messages to (call methods on) objects:
<sourcesyntaxhighlight lang=smalltalk>
" same as 'foo' at: 2 "
'foo' perform: #at: with: 2 " => $o "
</syntaxhighlight>
</source>
 
==References==
{{Reflist}}
<references/>
 
[[Category:Articles with example Ruby code]]