scottming

scottming

Is there a way to write a do_not match guard for map match?

I have some complex business logic have to verify a input map. And I don’t want to use nested control-flow. I expect a not_match guard to this things.

defmodule ElixirFun do
  @moduledoc """
  Documentation for ElixirFun.
  """

  @doc """
  Hello world.

  ## Examples

      iex> ElixirFun.hello()
      :world

  """
  def hello do
    :world
  end

  def hello(%{a: a, b: b}) do
    # match a and b
    IO.puts "Hello #{a}, #{b}"
  end

  def hello(%{a: a}) when not_match(%{b: _}) do
    # match a and do not match b
    IO.puts "Hello #{a}"
  end

  def hello{%{b: b}} when not_match(%{a: _}) do
    # match b and do not match a
    IO.puts "Hello #{b}"
  end

  def hello(%{} = params) do
    # others
    IO.inspect(params)
  end
end

I have read all of elixir tips and tried

defguard key_c_is_nil(params) when is_map(params) and get_in(params, [:b]) == nil

but it doesn’t work.

Marked As Solved

peerreynders

peerreynders

It just works without it - as long as you put everything in the right order.

defmodule ElixirFun do
  def hello(%{a: _a, b: _b} = m),
    do: IO.puts("1: #{inspect(m)}")

  def hello(%{a: _a} = m),
    do: IO.puts("2: #{inspect(m)}")

  def hello(%{b: _b} = m),
    do: IO.puts("3: #{inspect(m)}")

  def hello(%{} = m),
    do: IO.puts("4: #{inspect(m)}")
end

ElixirFun.hello(%{a: 1, b: 2, c: 3})
ElixirFun.hello(%{a: 4, c: 5})
ElixirFun.hello(%{b: 6, c: 7})
ElixirFun.hello(%{c: 8})
ElixirFun.hello(%{a: nil, b: nil, c: 9})
ElixirFun.hello(%{a: nil, c: 10})
ElixirFun.hello(%{b: nil, c: 11})
 elixir elixir_fun.exs
1: %{a: 1, b: 2, c: 3}
2: %{a: 4, c: 5}
3: %{b: 6, c: 7}
4: %{c: 8}
1: %{a: nil, b: nil, c: 9}
2: %{a: nil, c: 10}
3: %{b: nil, c: 11}

… keeping in mind that those four clauses all belong to one and the same hello/1 function.

It might as well be:

defmodule ElixirFun do
  def hello(m) do
    case m do
      %{a: _, b: _} ->
        IO.puts("1: #{inspect(m)}")

      %{a: _} ->
        IO.puts("2: #{inspect(m)}")

      %{b: _} ->
        IO.puts("3: #{inspect(m)}")

      %{} ->
        IO.puts("4: #{inspect(m)}")
    end
  end
end

Also Liked

peerreynders

peerreynders

In my view multiple function clauses are preferred because it chunks the logic into distinct, separate logical paths even if they do belong to the same function. With case do you are dealing with one monolithic piece of code which gets worse the more cases you add - apart from the temptation to put code before and after the case do expression.

But that’s not to say that case do is to be avoided - they both have their place. Coming from more traditional programming languages one would tend to gravitate towards case do because it’s reminiscent of switch while pattern matching in function heads just seems weird - but in most cases with exposure people come to prefer pattern matching in function heads because of the clean separation it brings.

For some more background:

And for completeness a multi-clause anonymous function:

defmodule ElixirFun do
  def make_hello() do
    fn
      %{a: _, b: _} = m ->
        IO.puts("1: #{inspect(m)}")

      %{a: _} = m ->
        IO.puts("2: #{inspect(m)}")

      %{b: _} = m ->
        IO.puts("3: #{inspect(m)}")

      %{} = m ->
        IO.puts("4: #{inspect(m)}")
    end
  end
end

hello = ElixirFun.make_hello()
hello.(%{a: 1, b: 2, c: 3})
hello.(%{a: 4, c: 5})
hello.(%{b: 6, c: 7})
hello.(%{c: 8})
hello.(%{a: nil, b: nil, c: 9})
hello.(%{a: nil, c: 10})
hello.(%{b: nil, c: 11})
axelson

axelson

Scenic Core Team

These clauses seem like they’ll do what you want:

  def hello(%{a: a, b: b}) do
  def hello(%{a: a}) do ...
  def hello(%{b: b} do ...
  def hello(%{} = params) do

Unless there’s something I’m missing? Don’t forget that function clauses are checked top to bottom (eliding some compiler optimizations)

Edit: thought if you wanted to ensure not nil then I would add a when not is_nil(a) and when not is_nil(b) to each clause (based on the binding it is using).

scottming

scottming

Thank you both.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
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
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
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
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39467 209
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
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement