- Clojure Tutorial
- Clojure - Home
- Clojure - Overview
- Clojure - Environment
- Clojure - Basic Syntax
- Clojure - REPL
- Clojure - Data Types
- Clojure - Variables
- Clojure - Operators
- Clojure - Loops
- Clojure - Decision Making
- Clojure - Functions
- Clojure - Numbers
- Clojure - Recursion
- Clojure - File I/O
- Clojure - Strings
- Clojure - Lists
- Clojure - Sets
- Clojure - Vectors
- Clojure - Maps
- Clojure - Namespaces
- Clojure - Exception Handling
- Clojure - Sequences
- Clojure - Regular Expressions
- Clojure - Predicates
- Clojure - Destructuring
- Clojure - Date & Time
- Clojure - Atoms
- Clojure - Metadata
- Clojure - StructMaps
- Clojure - Agents
- Clojure - Watchers
- Clojure - Macros
- Clojure - Reference Values
- Clojure - Databases
- Clojure - Java Interface
- Clojure - Concurrent Programming
- Clojure - Applications
- Clojure - Automated Testing
- Clojure - Libraries
- Clojure Useful Resources
- Clojure - Quick Guide
- Clojure - Useful Resources
- Clojure - Discussion
Clojure - Atoms swap!
Atomically swaps the value of the atom with a new one based on a particular function.
Syntax
Following is the syntax.
(swap! atom-name function)
Parameters − ‘atom-name’ is the name of the atom whose value needs to be reset. ‘function’ is the function which is used to generate the new value of the atom.
Return Value − The atom with the new value will be set based on the function provided.
Example
An example on how this is used is shown in the following program.
(ns clojure.examples.example (:gen-class)) (defn example [] (def myatom (atom 1)) (println @myatom) (swap! myatom inc) (println @myatom)) (example)
Output
The above program produces the following output.
1 2
From the above program you can see that the ‘inc’ (Increment function) is used to increment the value of the atom and with the help of the swap! function, the new value is automatically associated with the atom.
clojure_atoms.htm
Advertisements