In this guide, we will discuss Clojure send. This function is used to send across a value to the agent.
Syntax
Following is the syntax.
(send agentname function value)
Parameters − ‘agentname’ is the agent to which the send function is being redirected to. The ‘function’ is used to determine which way the value of the agent will be changed. In our case, we will use the addition + symbol to add a value to the existing value of the agent. ‘Value’ is the value passed to the function, which in turn will be used to update the value of the agent accordingly.
Return Value − Returns an agent object with a new value.
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) (send counter + 100) (println "Incrementing Counter") (println @counter)) (Example)
Output
The above program produces the following output.
0 Incrementing Counter 0
Please note the following about the above program.
- Since the send function is an asynchronous function, there is a time delay for when the value of the agent is updated. This is why we have added an extra ‘println’ statement to the program. This is to give the Clojure environment the time required to update the agent value accordingly.
- Secondly, when you run the above program, the program will not terminate immediately. This is because the Clojure environment does not know whether it is safe to shut down the agent. We will see how to shut down agents in the next function description.
Next Topic : Click Here
Pingback: Clojure - agent | Adglob Infosystem Pvt Ltd
Pingback: Clojure - Agents | Adglob Infosystem Pvt Ltd