Sanjibukai

Sanjibukai

Is it possible to partially pattern-match Lists as we do with Maps?

Hello everybody,

As it’s possible to partially pattern match with maps like so:

iex> %{b: 2} = %{a: 1, b: 2, c: 3}
%{a: 1, b: 2, c: 3}

Is it possible to do the same with Lists, e.g. like that:

iex> [2] = [1, 2, 3]
# MatchError

I guess that the inherent nature of linked lists (which make it easy to pattern-match heads/tails) might complicate things. Also I got the fact that in this case it might not make sense to pattern-match for variable binding . But it might be useful to pattern-match in this case for conditions/tests.

One can simply use Enum.member? but I don’t see an easy way to avoid conditions like we do when using pattern-matching in general or in functions argument.

Thank you very much for any details…

Marked As Solved

lucaong

lucaong

Or even easier, as you can use it in guards:

def some_func(x) when x in [1, 2, 3] do
  :present
end

def some_func(_) do
  :not_present
end

Also Liked

NobbZ

NobbZ

Yeah, this different implemantation introduces slightly “bugs” if not understood correctly:

def f(x) when x in [1,2,3], do: "123"
def f(x) when x in 4..6, do: "456"
def f(_), do: "nope"

IO.puts f(2) #=> 123
IO.puts f(2.0) #=> nope
IO.puts f(2.5) #=> nope
IO.puts f(5) #=> 456
IO.puts f(5.0) #=> 456
IO.puts f(5.5) #=> 456
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Hi @Sanjibukai you can match on the head and tail of a list, but there is no way to do a match which asks “Is this value anywhere in the list”.

[head | tail] = [1,2,3]
head #=> 1
tail #=> [2,3]
lucaong

lucaong

As @benwilson512 said, you cannot pattern match in the middle of a list. If you are looking for a convenient and readable way to check for inclusion, you can do this though:

2 in [1, 2, 3]

You can also use it in guards:

case 2 do
  x when x in [1, 2, 3] -> :yes
  _ -> :no
end
lucaong

lucaong

It’s interesting to notice how the guard is implemented. It is documented here and basically translates this:

when x in [1, 2, 3]

Into this:

when x === 1 or x === 2 or x === 3

The guard also works for ranges, with a different implementation, as the documentation shows.

lucaong

lucaong

Important thing to notice in order to understand the behavior of in with ranges, is that a range is an Enumerable of integers. Therefore, (0..10) includes 5 but not 5.5, nor 5.0 (see the is_integer(x) in the guard expansion).

That is consistent with how Enum.member? works on ranges:

Enum.member?(0..10, 5) #=> true
Enum.member?(0..10, 5.5) #=> false
Enum.member?(0..10, 5.0) #=> false

In other words, it could be considered surprising, but it is not a bug, it is intended behavior.

Where Next?

Popular in Questions Top

Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
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
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
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 Postg...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
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
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement