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.