concept loop in category elixir

appears as: loops, loop, The loop, loop
Elixir in Action

This is an excerpt from Manning's book Elixir in Action.

Now that you’re familiar with Elixir’s basic building blocks, it’s time to look at some typical low-level idioms of the language. In this chapter, we’ll deal with conditionals and loops. As you’ll see, these work differently than in most modern, imperative languages.

This can be used to implement a server process. You need to run the endless loop and wait for a message in each step of the loop. When the message is received, you handle it and then continue the loop. Let’s try this and turn the query example into a server process. The basic sketch is provided in the following listing.

To keep state in the process, you can extend the loop function with additional argument(s). Here’s a basic sketch:

def start do
  spawn(fn ->
 initial_state = ...    #1  
 loop(initial_state)    #2  
  end)
end

defp loop(state) do
  ...
 loop(state)    #3  
end

#1   Initializes the state during process creation
#2   Enters the loop with that state
#3   Keeps the state during the loop
Elixir in Action

This is an excerpt from Manning's book Elixir in Action.

Now that you’re familiar with Elixir’s basic building blocks, it’s time to look at some typical low-level idioms of the language. In this chapter, we’ll deal with conditionals and loops. As you’ll see, these work differently than in most modern, imperative languages.

This can be used to implement a server process. You need to run the endless loop and wait for a message in each step of the loop. When the message is received, you handle it and then continue the loop. Let’s try this and turn the query example into a server process. The basic sketch is provided in the following listing.

Here, you open the connection and then pass the corresponding handle to the loop function. In real life, instead of generating a random number, you’d use a database client library (such as ODBC) to open the connection.

Next, you need to modify the loop function.

Listing 5.6. Using the connection while querying (stateful_database_server.ex)

This is fairly straightforward. The loop function keeps the state (connection) as the first argument. You have to additionally extend the run_query function to use the connection while querying the database. The connection handle (in this case, a number) is included in the query result.

The loop handles various messages. The value message is used to retrieve the server’s state. Because you need to send the response back, the caller must include its pid in the message. Notice that the last expression of this block returns current_value. This is needed because the result of receive is stored in new_value, which is then used as the server’s new state. By returning current_value, you specify that the value request doesn’t change the process state.