does this work in clojure: "Symbols, however, don't typically evaluate to themselves1 As…
- User
does this work in clojure: "Symbols, however, don't typically evaluate to themselves1 As a rule, no rule without exception. Some symbols do evaluate to themselves, for example: t, nil, and keywords. . When lisp evaluates a symbol it assumes you are referring to a variable and tries to look up the value associated with that variable given your lexical context (unless the variable is declared special, in which case the dynamic environment). SLEEP-UNITS
(defmacro sleep-units (value unit) `(sleep (* ,value ,(case unit ((s) 1) ((m) 60) ((h) 3600) ((d) 86400) ((ms) 1/1000) ((us) 1/1000000)))))
To avoid quoting the unit, we need a macro. Unlike a function, a macro does not evaluate its arguments. Taking advantage of this fact, we replace the sleep-units% function with the sleep-units macro. Now we don't need to quote the unit:
(sleep-units .5 h)
Although the main purpose of this macro is to avoid having to quote the unit argument, this macro is even more efficient than the function because there is no run-time dispatch at all: the unit and therefore the multiplier are known at compile time. Of course whenever we discover this sort of too-good-to-be-true situation, it probably really is too good to be true. This gain in efficiency isn't free. By foregoing the run-time dispatch we have lost the ability to determine the time unit at run-time. This makes it impossible to execute the following code using our macro:"
- Assistant
- User
is using a symbol is better than using a keyword in this case?
- Assistant
In Clojure, using keywords is generally preferred over symbols for fixed, named constants like the units in your macro. Here's why:
-
Readability and Semantics: Keywords are self-evaluating in Clojure, which means they evaluate to themselves. This makes them perfect for cases where you're using fixed identifiers. Using keywords can make your code clearer and indicate that a fixed set of options is expected.
-
Performance: Keywords are slightly more performant than symbols for comparisons because they are typically interned, meaning each keyword is stored once and reused, allowing faster equality checks.
-
Intent: Using a keyword communicates that you are dealing with a known set of values or labels, while symbols often suggest variables or identifiers that might be bound to different values.
-