Symbols

Symbols

Robbert Haarman

2010-12-11

The symbol is an important data type of Scheme. Symbols are used as identifiers. They can act like names for variables or procedures. However, they can also be used just by themselves; for example, as an option to a procedure.

A symbol is written as a string of characters. Usually, these characters are letters, dashes, and numerals, but any character can be part of a symbol. Some example symbols are:

counter
string-append
set!
symbol?

Creating Symbols

There are various ways to create symbols. A symbol is created when you write one. For instance, if you write (define magic-value 12), you create the symbol magic-value and instruct define to bind the value 12 to it. You can also create symbols from strings, by using string->symbol. This way, you can put any character you like in the symbol.

Using Symbols

Normally, when the evaluator encounters a symbol, it evaluates the symbol and returns the value bound to it. The following code prints the value 12:

(define magic-value 12)
(display magic-value)

If you want the symbol itself to be returned, rather than its value, you can quote the symbol. This is accomplished by preceding the symbol name with a single quote (which is a shorthand for writing (quote symbol)). The following code prints foo:

(display 'foo)

If, in the above example, we had written (display foo) instead (without defining foo first), you would have gotten an error message to the effect that foo was an unbound symbol.

Testing for Symbolhood

You can test if something is a symbol by passing it as an argument to symbol?. For example:

(symbol? 'foo) => #t
(symbol? (string->symbol "bar")) => #t
(symbol? "baz") => #f
Valid XHTML 1.1! Valid CSS! Viewable with Any Browser