Why does Clojure have “keywords” in addition to “symbols”?

前端 未结 6 1812
暖寄归人
暖寄归人 2020-12-12 11:02

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\"

6条回答
  •  执笔经年
    2020-12-12 11:35

    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)
    

提交回复
热议问题