Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

conditional
elixir
with

What is Elixir with?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

svg viewer

Elixir has several control structures that allow the user to design the program flow. One of the most fundamental control structures of Elixir is with.

with statements are similar to case statements in that they execute tasks if the conditions are fulfilled. The key idea behind the with statement is establishing a Chain of functions and then feeding the output from the former function into the latter function if it Pattern Matches the predefined required output.

Format

The with control structure follows a rigid sequence of statements that are like a chain. In order to do the intended task, all the functions should return the desired output (Pattern Matching); otherwise, the program will be redirected away from the task to take the necessary actions.

svg viewer

Example

This example shows a naive program that takes customer_id and basket as input and then displays the bill of the basket. with calls two functions: registerID() and generateBill().

When dealing with the with structure, the output of the former functions is generally the input of the latter.

If the returned tuple from the functions match the pre-defined tuple, then the program proceeds to the do block. If either of the functions returned does not match the pre-defined tuple the program proceeds to the else block by default.

# Point of Sale
def pos(customer_id, basket) do
# Execute conditions in sequence
with {:ok, registered_id} <- registerID(customer_id),
{:ok, id_bill} <- generateBill(registered_id, basket)
#Print this if execution succeeds
do
IO.puts("Customer with ID #{id_bill.id} has bill ${id_bill.bill}")
#Otherwise, print this
else
nil -> IO.puts("No value returned")
{:error, error_message} -> "Error: #{error_message}"
end
end

RELATED TAGS

conditional
elixir
with
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring