Elisp: Symbol
What is Lisp Symbol
Lisp symbol is similar to other programing language's concept of identifiers. (that is, variable names and function names) But lisp symbol can be held unevaluated, and it can also store multiple values, including a Symbol Property List.
All lisp's variable names and function names are symbols.
For example,
(set (quote x) 3) ;; sets value 3 to symbol x ;; the x is a symbol, held from evaluation by quote function ;; because variable assignment is used often, a shorter syntax is introduced, the setq, which auto quote the first argument (setq x 3) ;; setq, set, quote, themselves are symbols
Usefulness of Symbols in Lisp
One major way lisp differs from most programing languages (such as Python JavaScript Golang Java ) is that the language is said to be symbolic. Meaning, the identifiers (function names, variable names) , are “symbols”. This means, variable or function name isn't just values, can be just the symbol itself.
For example, lets say you have a list of variables var with value val. You want to create new variable at run time, with name that's old var name joined by its value. The new variable name should be varval
(setq x 4) ;; create a new symbol, whose name is old name with its value appended, set the value to plus 1 of original (set (intern (concat (symbol-name (quote x)) (number-to-string (symbol-value (quote x))))) (1+ (symbol-value (quote x)))) (symbol-value (quote x4)) ;; 5
Transformation of Syntax, Lisp Macros
A language dealing with “symbols” directly means that transformation of expressions in source code is possible at run-time. (In lisp, this is the lisp macro feature, which is a limited form of term rewriting languages such as Wolfram Language .)
Convert Symbol to String
;; convert a symbol to string (symbol-name (quote defun))
Convert String to Symbol
;; convert a string to symbol ;; if the symbol does not already exist in obarray, create it, put it in obarray (intern "x") ;; if the symbol does not already exist in obarray, return nil (intern-soft "x")
Check If a Value is Symbol
symbolp
-
Return t if argument is a symbol.
(setq xx 3) (symbolp xx) ;; nil (symbolp (quote xx)) ;; t