in Uncategorized

Symbols vs. Keywords in Common Lisp

I was resuming work on my Sheepshead game today (more will be coming in time on this), and it occurred to me: what is the difference between a symbol and a keyword? If you type

(symbolp 'foo)

and

(symbolp :foo)

both return

T

but, if you type

(eq 'foo 'foo)
(eq :foo :foo)

both return

T

yet

(eq :foo 'foo)

returns

NIL

Finally, if you type

(symbol-name 'foo)

and

(symbol-name :foo)

both return

"FOO"

So, what gives? Both are symbols and symbols with the same print name, at that. The difference, is that keywords are all generated in the KEYWORD package, but symbols identified with the QUOTE operator are generated in the current package. So,

* (symbol-package 'foo)                                                                   
#<PACKAGE "COMMON-LISP-USER">

but

* (symbol-package :foo)                                                                   
#<PACKAGE "KEYWORD">

Just a quick little tidbit.

Write a Comment

Comment

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

 

  1. Yep, this is the difference, but it may be useful to give some indication on when to use keywords, symbols or strings.

    If you need to preserve case when printing, you have to use strings:

    (string ‘TeST)
    (symbol-name ‘TeST)
    (string :TeST)
    (symbol-name :TeST)
    all return “TEST”

    If case is unimportant, you can use either a symbol or a keyword. Which one?
    Here’s what the CL Hyper Spec tells about:

    … use keywords when communicating between programs in different packages…
    … the mechanism for passing keyword parameters in a call uses keywords to name the corresponding arguments…
    …It is generally best to confine the use of keywords to situations in which there are a finitely enumerable set of names to be selected between. For example, if there were two states of a light switch, they might be called :on and :off.

    In situations where the set of names is not finitely enumerable (i.e., where name conflicts might arise) it is frequently best to use symbols in some package other than KEYWORD so that conflicts will be naturally avoided. For example, it is generally not wise for a program to use a keywor as a property indicator, since if there were ever another program that did the same thing, each would clobber the other’s data.