Cifer-Y

Cifer-Y

How to deal with this pattern elegant?

I apologize for not being able to describe my question clearly in the title.
I’m not sure how to name this coding pattern.

Recently I found I always write code like this pattern:

result = []
result = if abc, do: [abc | result], else: result
result = if ghi, do: [ghi | result], else: result

or

result = %{}
result = if abc, do: Map.merge(result, %{abc: abc}), else: result
result = if ghi, do: Map.merge(result, %{ghi: ghi}), else: result

These are just examples.
In actual code, the situation may be more complex but follow the same pattern.
Is there an elegant solution to handle such scenarios?

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

for is also pretty nice for these:

for item <- list, item, do: item

for {k, v} <- item, v, into: result, do: {k, v}

Also Liked

codeanpeace

codeanpeace

Enum.reduce/3 is another approach.

data = [abc, ghi, ...]
result = Enum.reduce(data, [], fn x, acc -> if x, do: [x | acc], else: acc end)

# or with a helper function and pattern matching
result = Enum.reduce(data, [], fn x, acc -> maybe_prepend(acc, x) end)
def maybe_prepend(result, data) when is_nil(data), do: result
def maybe_prepend(result, data), do: [data | result]
data = [abc: "abc", ghi: "ghi", ...]
result = Enum.reduce(data, %{}, fn x, acc -> if {key, value} = x, do: Map.put(acc, key, value), else: acc end)

# or with a helper function and pattern matching
result = Enum.reduce(data, %{}, fn x, acc -> maybe_merge(acc, x) end)

def maybe_merge(result, data) when is_nil(data), do: result
def maybe_merge(result, {key, value}), do: Map.merge(result, %{key => value})
fceruti

fceruti

Yours seems fine, but another way you could consider is using pipes:

result
|> maybe_abc(args)
|> maybe_ghi(args)

...

def maybe_abc(result, %{matching: true} = args), do: [args | results]
def maybe_abs(result, _args), do: results 

def maybe_ghi(result, %{matching: true} = args), do: [args | results]
def maybe_ghi(result, _args), do: results
code-shoily

code-shoily

Love the reduce approach! :+1:

Where Next?

Popular in Questions 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
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
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
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
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
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

WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
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...
274 41539 114
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
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
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
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement