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

Viewed 26709

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)?

6 Answers

Keywords are global, symbols are not.

This example is written in JavaScript, but I hope it helps to carry the point across.

const foo = Symbol.for(":foo") // this will create a keyword
const foo2 = Symbol.for(":foo") // this will return the same keyword
const foo3 = Symbol(":foo") // this will create a new symbol
foo === foo2 // true
foo2 === foo3 // false

When you construct a symbol using the Symbol function you get a distinct/private symbol every time. When you ask for a symbol via the Symbol.for function, you will get back the same symbol every time.

(println :foo) ; Clojure
System.out.println(RT.keyword(null, "foo")) // Java
console.log(System.for(":foo")) // JavaScript

These are all the same.


Function argument names are local. i.e. not keywords.

(def foo (fn [x] (println x))) ; x is a symbol
(def bar (fn [x] (println x))) ; not the same x (different symbol)
Related