Cifer-Y

Cifer-Y

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?

Showing Posts 1 to 8

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

Assuming abc and ghi are nil (for the if to fail)… I would do something like:

[abc, bcd, cde, efg, fgh, ghi]
|> Enum.reject(&is_nil/1)
|> Kernel.++(result)

for maps:

%{abc: abc, bcd: bcd, cde: cde, efg: efg}
|> Map.reject(fn {_k, v} -> is_nil(v) end)
|> Map.merge(result)
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})
code-shoily

code-shoily

Love the reduce approach! :+1:

dimitarvp

dimitarvp

Very similar to what @fceruti proposes but with only generic function:

defmodule Xyz do
  def prepend_if_truthy(list, condition, value) do
    if condition do
      [value | list]
    else
      list
    end
  end

  def test_stuff() do
    [:general, :kenobi]
    |> prepend_if_truthy("sure", :there)  # everything that's not `nil` or `false` is "truthy"
    |> prepend_if_truthy(nil, "hmmm")
    |> prepend_if_truthy(false, "nope")
    |> prepend_if_truthy(is_number(0.0), :hello)
  end
end

Then Xyz.test_stuff() will yield [:hello, :there, :general, :kenobi]

:smiley:

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}
dimitarvp

dimitarvp

Maybe one day InTheFarFuture™, for example a few weeks before I kick the bucket, I’ll have finally remembered that Collectable exists.

Cifer-Y

Cifer-Y OP

This is truly remarkable, and I am disappointed that I was not previously aware of this. :rofl:

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews