Symbols in Clojure

前端 未结 2 1666
南旧
南旧 2020-12-07 11:31

What is the rationale for Symbols in Clojure to be bound to an underlying object and have an optional separate value ? Perhaps something elementary I am missing but would be

2条回答
  •  遥遥无期
    2020-12-07 12:17

    There may be some confusion here from the different usages of the term "symbol" in Common Lisp and in Clojure.

    In Common Lisp, a "symbol" is a location in memory, a place where data can be stored. The "value" of a symbol is the data stored at that location in memory.

    In Clojure, a "symbol" is just a name. It has no value.

    When the Clojure compiler encounters a symbol, it tries to resolve it as

    1. a Java class name (if the symbol contains a dot)
    2. a local (as with "let" or function parameters)
    3. a Var in the current Namespace
    4. a Var referred from another Namespace

    The Var, as a previous poster pointed out, represents a storage location.

    There are good reasons why Clojure separates Vars from Symbols. First, it avoids the annoyance of Common Lisp's automatically-interned symbols, which can "pollute" a package with unwanted symbols.

    Secondly, Clojure Vars have special semantics with regard to concurrency. A Var has a exactly one "root binding" visible to all threads. (When you type "def" you are setting the root binding of a Var.) Changes to a Var made within a thread (using "set!" or "binding") are visible only to that thread and its children.

提交回复
热议问题