What is the send method in Clojure?

Overview

Clojure variables are immutable. We can use an agent to mutate the storage location alongside the use of functions. The changed state of the agent is then returned, as we'll see in the example below. In Clojure, we use the send method to send the value of a running agent.

Syntax

(send agentname function value)
Syntax of the send method

Parameters

The send method receives three parameters;

  1. agentname: The name of the agent we are sending value to.
  2. function: The method which we will use to send the value, the example we would see in this shot we use the + to carry out an additional operation.
  3. value: The value we will send

Return value

The send method returns an agent with a changed value.

(ns clojure.examples.example
(:gen-class))
(defn func []
(def names (agent 10))
(println @names)
(send names + 200)
(await-for 50 names)
(println @names)
(shutdown-agents))
(func)

Explanation

  • Line 3: We define a function func.
  • Line 4: We define a names variable with the agent method and we set the agent state to 10.
  • Line 5: We print the names variable
  • Line 6: We use the send method to change the value of the names variable. Here we're adding 200 to the initial 10.
  • Line 7: We use the await-for method to cause a delay of 50 seconds so that the send method executes properly since it takes time to process.

To learn about the await-for method visit this link

  • Line 8: We print the variable names. Note that the names variable is now 210 instead of 10 because of the help of the send method.
  • Line 9: When we now call the shutdown-agents method all the agents are stopped if not an error will be thrown. You can try removing the line with the shutdown-agents code.

To learn about the shutdown-agents method visit this link

  • Line 10: We call the function func.

Free Resources