lanycrost

lanycrost

How To Implement if...else if...else condition

Hi everyone!

I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work properly for me.
I want implement this logic.

if *** do

else if *** do

else

end

I try use cond condition, but i don’t know how implement else logic to this control flow structures.

Thanks!

Marked As Solved

NobbZ

NobbZ

def userselect(%{id: id} = user), do: …
def userselect(%{email: email} = user), do: …
def userselect(%{username: username} = user), do: …
def userselect(_), do: …

Since you now have a match on id, email, or username you may be able to even rewrite the “inner” block a bit.

Since all the case are identical, I’d even move them into a helper function, making your blocks look like this:

defp sel_user(nil), do: {:error, "Something went wrong"}
defp sel_user(user), do: {:ok, user}

def userselect(%{id: id}), do: User |> Repo.get(id) |> sel_user()
def userselect(%{email: email}), do: User |> Repo.get(email) |> sel_user()
def userselect(%{username: username}), do: User |> Repo.get(username) |> sel_user()
def userselect(_), do: sel_user(nil)

Next step were to create those function heads from a list using metaprogramming, they are the same except for the key to match on… But to be honest, I’d do that only for more than 5 keys, you don’t gain much for less, maybe even you loose a lot if meta-ing to early :wink:

14
Post #6

Also Liked

peerreynders

peerreynders

iex> cond do
...>   2 + 2 == 5 ->                                # 1 if expression (equivalent)
...>     "This is never true"                       # 1 
...>   2 * 2 == 3 ->                                # 2 if-else expression (equivalent)
...>     "Nor this"                                 # 2
...>   true ->                                      # 3 else expression (equivalent)
...>     "This is always true (equivalent to else)" # 3
...> end
"This is always true (equivalent to else)"

It’s important to remember that cond, case and even if are expressions , not statements (i.e. not control flow structures) - think: ternary operator in JavaScript, (C, C++, C#, Java) - i.e. they are fundamentally designed to return a value - though the compiler doesn’t yell at you if you ignore the returned value. Functions with multiple clauses work similarly as functions always return values. Many situations can be implemented with either case expressions or multi-clause functions and both support guards which is essentially is a condition that refines the pattern match.

13
Post #4
AstonJ

AstonJ

I had a feeling multiple def clauses might be more appropriate :003:

@NobbZ’s code is much more readable/refactorable/maintainable and the preferred way of doing things (according to @pragdave) because each function is responsible only for one thing :023:

NobbZ

NobbZ

Any reason why you don’t simply use nested if, if you need a nested if?

And an “else” branch in a cond is simply true.

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
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
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
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

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
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
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