Welcome! Please see the About page for a little more info on how this works.

0 votes
in Syntax and reader by

Hello dear Clojurians!
What is the difference between "keyword" and "atom"?
Sorry, I'm a total newbie :-)

2 Answers

+2 votes
by
selected by
 
Best answer

Keywords are symbolic identifiers that evaluate to themselves. They are often used as keys in maps to name attributes or as enumerated values.

For example, in the map {:first-name "SpongeBob", :last-name "SquarePants"} there are two entries using the keys :first-name and :last-name.

See: https://clojure.org/reference/data_structures#Keywords

Atoms are effectively boxes that hold a value that can be atomically updated by applying a function to the existing value. For example, you could make a counter out of an atom and then increment it (safely from multiple threads if needed).

(def counter (atom 0))
(swap! counter inc) ;; increment counter
@counter ;; read counter: 1

See: https://clojure.org/reference/atoms

by
So... Atom is a variable which are mutable??
by
Yes, atoms provide controlled mutability -- thread-safe when updated by applying a function to the previous value. See also Refs and Agents -- https://clojure.org/reference/refs and https://clojure.org/reference/agents
by
Thank you!  :-)
0 votes
by

Ignoring atoms completely, here's an informal perspective on keywords:

I like to think of keywords conceptually like a string/symbol hybrid with special superpowers. Like symbols, they're restricted to certain characters (notably, no spaces allowed) and can be namespaced: :myproject.api/foo. Like strings, they're really just a data primitive.

The main keyword superpower is that they can be called as functions to get values out of associative data structures like hash-maps: (:foo {:foo 42 "bar" 36}) => 42 and sets: (:foo #{:foo :bar}) => :foo. You can't use strings or numbers as functions.

Here's a helpful StackOverflow answer about why keywords exist in Clojure: https://stackoverflow.com/a/11655615

by
Thank you!  :-)
...