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.

lanycrost

lanycrost

Of course!

def userselect( user ) do
    cond do
      Map.has_key?( user, :id ) ->
        sel_user = User |> Repo.get( user.id )

        case sel_user do
          nil -> { :error, "Something went wrong!" }
          _ -> { :ok, sel_user }
        end
      Map.has_key?( user, :email ) ->
        sel_user = User |> Repo.get_by( email: user.email )

        case sel_user do
          nil -> { :error, "Something went wrong!" }
          _ -> { :ok, sel_user }
        end
      Map.has_key?( user, :username ) ->
        sel_user = User |> Repo.get_by( username: user.username )

        case sel_user do
          nil -> { :error, "Something went wrong!" }
          _ -> { :ok, sel_user }
        end
      true ->
        { :error, "It's immposible to select a user using this parameter." }
    end
  end
AstonJ

AstonJ

What you are trying to do might be better as something else (such as cond or multiple function clauses) can you paste your code so we can take a look?

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
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
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
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
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
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
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
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement