Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

lisp - Why does Clojure have "keywords" in addition to "symbols"?

I have a passing knowledge of other Lisps (particularly Scheme) from way back. Recently I've been reading about Clojure. I see that it has both "symbols" and "keywords". Symbols I'm familiar with, but not with keywords.

Do other Lisps have keywords? How are keywords different from symbols other than having different notation (ie: colons)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's the Clojure documentation for Keywords and Symbols.

Keywords are symbolic identifiers that evaluate to themselves. They provide very fast equality tests...

Symbols are identifiers that are normally used to refer to something else. They can be used in program forms to refer to function parameters, let bindings, class names and global vars...

Keywords are generally used as lightweight "constant strings", e.g. for the keys of a hash-map or the dispatch values of a multimethod. Symbols are generally used to name variable and functions and it's less common to manipulate them as objects directly except in macros and such. But there's nothing stopping you from using a symbol everywhere you use a keyword (if you don't mind quoting them all the time).

The easiest way to see the difference is to read Keyword.java and Symbol.java in the Clojure source. There are a few obvious implementation differences. For example a Symbol in Clojure can have metadata and a Keyword can't.

In addition to single-colon syntax, you can use a double-colon to make a namespace-qualified keyword.

user> :foo
:foo
user> ::foo
:user/foo

Common Lisp has keywords, as do Ruby and other languages. They are slightly different in those languages of course. Some differences between Common Lisp keywords and Clojure keywords:

  1. Keywords in Clojure are not Symbols.

    user> (symbol? :foo)  
    false
    
  2. Keywords don't belong to any namespace unless you specifically qualify them:

    user> (namespace :foo)
    nil
    user> (namespace ::foo)
    "user"
    

(Thanks Rainer Joswig for giving me ideas of things to look at.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...