hariharasudhan94

hariharasudhan94

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

Marked As Solved

LostKobrakai

LostKobrakai

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

Also Liked

OvermindDL1

OvermindDL1

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:

peerreynders

peerreynders

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}
gregvaughn

gregvaughn

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”}

Where Next?

Popular in Questions Top

chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 127536 1222
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement