How to use return statement with if condition in elixir?

lets say i have a sample like

a = 20; b = 10;
if (a > b) do
{:ok, "a"}
end

if (a < b) do
{:ok, b}
end

if (a == b) do
{:ok, "equal"}
end

when i run this code first condition satisfied ,instead of returning {:ok, "a"} tuple it starts executing next block of code, how can i stop the execution once first condition is met, and return result

You canā€™t return early in elixir, but thereā€™s another constuct for such operations:

cond do
  a > b -> {:ok, "a"}
  a < b -> {:ok, "b"}
  a == b -> {:ok, "equal"}
end
5 Likes

To be more specific, there are no statements, everything returns something, including those lines, they just return it ā€˜upā€™ (so the if returns it, but the if is not being assigned to anything so it vanishes). :slight_smile:

2 Likes

You could use a cond, as shown above, or even different named function heads with pattern matching

def compare(a, a), do: {:ok, ā€œequalā€}
def compare(a, b) when a > b, do: {:ok, ā€œaā€}
def compare(a, b) when a < b, do: {:ok, ā€œbā€}

1 Like

Just to add to the spectrum (i.e. Iā€™m not recommending this) I see Gregā€™s suggestion as a ā€œcleaned upā€ version of

a = 20 
b = 10

result = 
  case {a,b} do
    {c,c} -> "equal"
    {c,d} when c > d -> "a"
    {c,d} when c < d -> "b"
  end
reply = {:ok, result}

IO.inspect(reply)

which could also be written as

a = 20 
b = 10

result = 
  case {a,b} do
    _ when a > b -> "a"
    _ when a < b -> "b"
    _ -> "equal"
  end
reply = {:ok, result}

IO.inspect(reply)

leading to the accepted solution

a = 20 
b = 10

result = 
  cond do
    a > b -> "a"
    a < b -> "b"
    true -> "equal"
  end
reply = {:ok, result}

IO.inspect(reply)

And if do always has a ā€œsecondā€ value it evaluates to when the condition is false - it will return nil

a = 10 
b = 20

value1 = 
  if a > b do
    "a"  
  end
  
value2 = 
  cond do
    a > b -> "a"
    true -> nil
  end

IO.inspect({value1,value2})

> {nil, nil}
2 Likes

This is not equivalent to the OPs code, since a == b is true for a = 1; b = 1.0, but your code would run into a function clause error.

Youā€™ve got quite the eye for detail! And that brings up a great point: which one is more correct is going to depend on the actual requirements of the problem. Knowing multiple approaches to a problem can help choose the one that best matches the requirements.