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

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 92995 915
New
caslu
I want to open this thread for you all to discuss and help those who really like Ash but are still hesitant to use it in a real project. ...
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
GES233
I’m posting this in response to Jose’s recent tweet (Cr. link) : People are sleeping on Elixir for a coding harness: Hot-code swappi...
New
_mfierro
Hello, I wrote Stop My Hand, a Scattergories-like web application using Phoenix/LiveView as my learning project for Elixir (after readin...
New
marciol
It would be helpful to have a list of companies worldwide that hire engineers without prior experience in Elixir. Often, it can be quite ...
New
durvia
Anyone running long-lived stateful processes on BEAM? We’re building an AI agent runtime and would love to compare notes. We’re a small ...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
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
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & 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