Hacker News new | ask | show | jobs
by nine_k 1534 days ago
I'd say that Ruby has symbols because Ruby has mutable strings.

If your strings are immutable and interned, they are as good as symbols; this is why Python does not have symbols.

ECMASript introduced symbols because JavaScript strings, while immutable, are not necessarily interned. Symbols are much cheaper to compare for equality: you only need to compare the pointers / ids, not actual string bytes.

Lisp has symbols for the same reason: Lisp strings are vectors, which are also mutable.

3 comments

Lisp has symbols, because they were used in symbolic expressions (s-expressions) as named entities. In the programming language Lisp these symbols serve also as identifiers for functions, variables and other things. Thus a symbol originally had an internal structure made of an association list (a list of keys and values). That association list then had various entries, including a print name -> the thing to print when a symbol gets externalized. Since symbols can serve as function names, these symbols also had functions stored in their association list. Different function types could be stored under different keys.

Since Lisp symbols serve a central role as identifiers and structured objects, they are not like what Ruby uses. Lisp uses symbols also for named interned things, but that is only one purpose.

In Common Lisp symbols have a name, a value, a function, a package and a property list (a list of keys and their values). By default in a call like (mult 1 2 3), the global function will be retrieved from the symbol and the function will be called with the arguments. The property list sometimes will be used by an IDE to store information about the symbol: like where it was defined, what its definition is and similar.

At least in V8 they are last I checked. The symbols feature is a property privacy feature. A symbol can be treated as a private secret owned by a library thus restricting access to a property on a shared object.
This is untrue. Symbols provide no privacy. They provide a mechanism to avoid collisions. You can even ask an object for its symbol properties: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
JS symbols are the opposite of what you are saying.

If you have five instances of `:foo` in Ruby, you can guarantee they will be IDENTICAL.

If you have five instances of `Symbol('foo')` in Javascript, you are guaranteed they will be completely DIFFERENT.

JS symbols are like Common Lisp's `gensym` which it uses to guarantee macro variables won't collide with existing variable names.