Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

elixir
loop

What are loops in Elixir?

Educative Answers Team
svg viewer

What are loops?

Loops are control structures used to repeat a particular block of statements until a specific condition is met. The condition can be a comparison between objects or an iteration between a range.

Unlike some other languages, it is not possible to iterate over a counter to run a loop in Elixir.

// python
for i in range(0,10)

// c++
for(int i = 0; i < 10; i++){}

This is because variables in Elixir are immutable. Immutable variables are variables that cannot change their state after initialization.

Implementation

What’s the solution? Recursion!

In Elixir, to loop through a range, you need to use recursion. Recursion is the method of making a function call itself until a base-case is reached.

Example

defmodule LoopModule do

  # Base case to terminate when string is sliced n times
  def sliceHeadnTimes(_, n) when n <= 0 do
    nil
  end

  # Base case to terminate when string is empty
  def sliceHeadnTimes(string, _) when string === "" do
    nil
  end

  # Main recursion-loop
  def sliceHeadnTimes(string, n) do
    sliced_string = String.slice(string, 1..-1)
    IO.puts(sliced_string)
    sliceHeadnTimes(sliced_string, n-1)
  end

  
end

string = "edpresso"
IO.puts("String to slice: #{string}")
LoopModule.sliceHeadnTimes(string, 4)

Explaination

The module above has a function that loops n times to slice the head of a string. To do that, we have a function named sliceHeadnTimes(), which takes a string and an integer as parameters. sliceHeadnTimes() is recursively called until either of the following base-cases are hit.

  • The number specified number of iterations have completed.
  • The string is empty.

This is just one example, but you can be creative with recursive-loops to solve your problems!

RELATED TAGS

elixir
loop
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring