vans163

vans163

So when writing logic that is too complex for a case, (usually with C it will look like a function with return statements scattered throughout) a cond is used.

Now one thing that irks me about cond is, you cannot assign variables in the branches.

Multis for example will fit the bill, but they are a bit heavyweight for the simple usecase of just wanting to assign a variable in a cond.

Here is an example:

inventory = state.inventory
cond do
    Enum.find(inventory, & &1.name == "Moon Cake") ->
      moon_cake = Enum.find(inventory, & &1.name == "Moon Cake")
      {:eat, moon_cake.id}
    (Enum.find(inventory, & &1.name == "Space Cake")[:count]||0) > 10 ->
      space_cake = Enum.find(inventory, & &1.name == "Space Cake")
      {:eat, space_cake.id}
   true -> 
     nil
end

But wish we can do

cond do
    moon_cake = Enum.find(inventory, & &1.name == "Moon Cake") ->
      {:eat, moon_cake.id}
    (space_cake = Enum.find(inventory, & &1.name == "Space Cake"))[:count]||0 > 10 ->
      {:eat, space_cake.id}
   true -> 
     nil
end

Is there any good solutions out there? The net win is that, the cond does not go further, so as to prevent multiple iterations of the inventory if an earlier clause succeeded.

Showing Posts 1 to 10

sfusato

sfusato

Wouldn’t Enum.find_value/3 be more appropriate here? Something along the lines:

Enum.find_value(inventory, fn
  %{id: id, name: "Moon Cake"} -> {:eat, id}
  %{id: id, name: "Space Cake", count: count} when count > 10 -> {:eat, id}
  _ -> nil
end)
vans163

vans163 OP

Enum.find_value is an interesting one, I will start using this thanks! But not fitting to this usecase.

EDIT: Oh a problem with find_value is priority, say we wanna ALWAYS eat the Moon Cake (if we have it) before the Space Cake. Depending on the order of the elements in the inventory that is not guaranteed.

In this particular case imagine the conditional is more complex with many more checks, for example:

cond do
    is_dead(state) -> nil
    is_full(state) -> nil
   ..
end

Using Enum.find_value we will be checking is_dead and is_full on every iteration.

aenglisc

aenglisc

You can do something along the lines of

Enum.reduce_while(inventory, nil, fn                                                                                                                       
  %{id: id, name: "Moon Cake"}, _ -> {:halt, {:eat, id}}                                                                                                     
  %{id: id, name: "Space Cake", count: count}, _ when count > 10 -> {:cont, {:eat, id}}                                                                      
  _, acc -> {:cont, acc}                                                                                                                                     
end)
tfwright

tfwright

For anyone else like myself who somehow missed this syntax when they were in elixir school: pattern matching on anonymous functions

I am now cringing thinking of all the fn arg -> case arg do end end in my code :man_facepalming:

vans163

vans163 OP

This is getting there but imagine you have an inventory and warehouse now. You want to check if the Moon Cake is in the inventory, then also in the warehouse, in the same cond. So reducing just the inventory is not enough.

@tfwright, Haha its nice.

aenglisc

aenglisc

Sounds to me like you can just reduce both in one go.

vans163

vans163 OP

I am not seeing it, at least not cleanly. And again the reduce_while loses the order, so if we want to ALWAYS eat Moon Cake BEFORE Space Cake if we have both, the reduce_while does not fit the bill.

aenglisc

aenglisc

It doesn’t, it terminates as soon as you find a Moon Cake.

[
  %{count: 12, id: 1, name: "Space Cake"},
  %{id: 2, name: "Moon Cake"},
  %{count: 8, id: 3, name: "Space Cake"},
  %{count: 16, id: 4, name: "Space Cake"},
  %{count: 3, id: 5, name: "Space Cake"},
  %{count: 11, id: 6, name: "Space Cake"},
  %{count: 1, id: 7, name: "Space Cake"},
  %{count: 15, id: 8, name: "Space Cake"},
  %{count: 7, id: 9, name: "Space Cake"},
  %{count: 18, id: 10, name: "Space Cake"}
]
iex(19)> Enum.reduce_while(inventory, nil, fn                                                                                                                       
...(19)>   %{id: id, name: "Moon Cake"}, _ -> {:halt, {:eat, id}}                                                                                                     
...(19)>   %{id: id, name: "Space Cake", count: count}, _ when count > 10 -> {:cont, {:eat, id}}                                                                      
...(19)>   _, acc -> {:cont, acc}                                                                                                                                     
...(19)> end)
{:eat, 2}
vans163

vans163 OP

Sigh, but this is just fitting a ironcast mold to the exact problem, with the cont and halt. Okay new requirement there is a Blackhole Cake now. And it should be prioritized last (so if have Moon Cake, Space Cake and Blackhole Cake) eat only 1 in that priority.

All of a sudden this new requirement which is very practical as the system grows is going to lead to a nasty refactor.

aenglisc

aenglisc

Does not sound like a big deal honestly.
Store the whole map in the acc and build your logic around that.

Where Next? Top

Trending in Discussions Top

cblavier
Hey there, It’s been more than a year since we started using LiveView as our main UI library and building a whole library of UI componen...
New
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
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
achempion
I’ve been using Emacs as my main code editor for more than a two years. It’s a custom build version although I’ve tried doom emacs and sp...
New
axelson
Hi there! :wave: @frigidcode and I (but mostly him) have been running an Elixir Book club, we’re almost done with Designing Elixir Syste...
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
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
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
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
georgeguimaraes
Just published claude-code-elixir, a plugin marketplace for Claude Code with Elixir support. These are the plugins I’ve been using for my...
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews