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;
agentname: The name of the agent we are sending value to.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.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
namesvariable with theagentmethod and we set the agent state to10. - Line 5: We print the
namesvariable - Line 6: We use the
sendmethod to change the value of thenamesvariable. Here we're adding200to the initial10. - Line 7: We use the
await-formethod to cause a delay of50seconds so that thesendmethod executes properly since it takes time to process.
To learn about the
await-formethod visit this link
- Line 8: We print the variable
names. Note that thenamesvariable is now210instead of10because of the help of thesendmethod. - Line 9: When we now call the
shutdown-agentsmethod all the agents are stopped if not an error will be thrown. You can try removing the line with theshutdown-agentscode.
To learn about the
shutdown-agentsmethod visit this link
- Line 10: We call the function
func.