denna

denna

How to filter a list of nils

I have sometimes list with elements of different type.
for example nil and tuple
the thing is that the filter function is a bit long. I wonder if this can be written shorter. particularly because i don’t care about failing cases.

Enum.filter(list_of_nils_and_tuples, fn elem ->
        if(is_nil(elem)) do
          false
        else
          {id, _v} = elem
            some_complicated_test(id)
        end
      end)

The question is maybe more about how to avoid if else structures in elixir?

Most Liked

stefanchrobot

stefanchrobot

Pattern matching to the rescue!

Enum.filter(list_of_nils_and_tuples, fn 
  nil -> false
  {id, _v}  -> some_complicated_test(id)
end)
kokolegorille

kokolegorille

You can, but You also apply a transformation at the same time…

list_of_nils_and_tuples
|> Enum.filter(& &1)     # drop falsy value
|> Enum.map(& some_complicated_test(elem(&1, 0)))

You can also define some_complicated_test to return false when nil is passed, and use it as the filter function.

kendocode

kendocode

I just had to do something similar and was looking for something like Enum.compact().
I ended up using a comprehension with pattern matching as well, but you don’t need the match operator (=) or the guard. The {id, _v} itself is already doing the work. Example:


iex(0)> list = [nil, nil, {1,2}, nil, {3,4}]
[nil, nil, {1, 2}, nil, {3, 4}]

iex(1)> for {id, _v} <- list, do: id
[1, 3]
slouchpie

slouchpie

Another option is to to use a comprehension:

for {id, _v} = nil_or_tuple <- list_of_nils_and_tuples, not is_nil(nil_or_tuple), do: some_complicated_test(id)
brettbeatty

brettbeatty

You can also filter/reject multiple times, though you may want to use stream instead of enum for longer lists.

list_of_nils_and_tuples
|> Enum.reject(&is_nil/1)
|> Enum.filter(fn {id, _v} -> some_complicated_test(id) end)

Where Next?

Popular in Questions Top

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
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
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
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
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
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
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
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
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
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

Other popular topics Top

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
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
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
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
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
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
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
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
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
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

We're in Beta

About us Mission Statement