Clojure - agent


Advertisements

An agent is created by using the agent command.

Syntax

Following is the syntax.

(agent state)

Parameters − ‘state’ is the initial state that should be assigned to the agent.

Return Value − Returns an agent object with a current state and value.

Example

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (def counter (agent 0))
   (println counter))
(Example)

Output

The above program produces the following output.

#object[clojure.lang.Agent 0x371c02e5 {:status :ready, :val 0}]

Just like the atom data type, you can see that the agent also has a status and a value associated with it. To access the value of the agent directly you need to use the @symbol along with the variable name.

Example

An example on how this is used is shown in the following program.

(ns clojure.examples.example
   (:gen-class))
(defn Example []
   (def counter (agent 0))
   (println @counter))
(Example)

Output

The above program produces the following output.

0

You can clearly see from the above program that if you have append the @ symbol like @counter, you will get access to the value of the agent variable.

clojure_agents
Advertisements