What are pipelines in Elixir?

Similar to the pipe operator in Unix, the pipe operator takes the return value from the expression on its left and provides it as the first parameter to the function call on its right.

The pipe operator is denoted by |> in Elixir.

Code example

Let’s understand the pipeline with an example.

Consider that the following operations have to be performed on a given string:

  1. Remove leading and trailing spaces
  2. Convert only the first character of the string to uppercase
  3. Concat another string with it

The above three operations can be performed in different steps as different expressions, with the result of each step stored in a temporary variable.

We can also perform the sequence of the above operations via a pipe operator.

Let’s see the following code:

platform = " The educative platform "
IO.puts(["Original string - ", platform])
temp = String.trim(platform)
temp = String.capitalize(temp)
temp = String.split(temp, " ")
IO.puts "Final string - "
IO.inspect temp
IO.puts "-----------"
IO.puts "Using pipe operator"
new_temp = platform |> String.trim() |> String.capitalize() |> String.split(" ")
IO.inspect new_temp

Code explanation

  • Line 1: A string is defined.
  • Line 5: The trim() function is applied and the result is stored in the temp variable.
  • Line 7: The capitalize() function is applied and the result is stored in the temp variable.
  • Line 9: The split() function is applied and the result is stored in the temp variable.
  • Line 17: We can combine strings in lines 5,7, and 9 as a single expression using the pipe operator.

Copyright ©2024 Educative, Inc. All rights reserved