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

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews