Hello,
I work with Riccardo so I frequently experience the same issue.
I really like José and Piotr solutions, however I'd like to point out that
they might introduce some clutter and in real world code they might cause
long lines that are broken from the formatter, which can be ugly when using
Forgive me because I’m not 100% sure what you mean, but you can do this:
def update_nil_values(map, new_values, into \\ %{}) do
Enum.reduce(map, into, fn
{key, nil}, acc -> Map.put(acc, key, Map.get(new_values, key))
{key, value}, acc -> Map.put(acc, key, value)
end)
end
Enum.reduce() does not compose as well when you have conditional Map.put
spread over multiple private functions.
On Fri, Jun 5, 2020 at 5:20 PM Adam Lancaster
wrote:
> Thinking about it, can you solve the original problem with reduce?
>
> ```elixir
> new_values = %{
> foo: 10,
> bar: 20
> }
Thinking about it, can you solve the original problem with reduce?
```elixir
new_values = %{
foo: 10,
bar: 20
}
Enum.reduce(map, %{}, fn
{key, nil}, acc -> Map.put(acc, key, Map.get(new_values, key))
{key, value}, acc -> Map.put(acc, key, value)
end)
```
Best
Adam
> On
We have something similar in our code base we called the Maybe.Pipe: ~>
> On 5 Jun 2020, at 14:41, Piotr Szmielew wrote:
>
> maybe it should be called run_if? so, something like this:
>
> defmacro run_if(piped_value, condition, fun) do
> quote do
> if unquote(condition) do
>
maybe it should be called run_if? so, something like this:
defmacro run_if(piped_value, condition, fun) do
quote do
if unquote(condition) do
unquote(fun).(unquote(piped_value))
else
unquote(piped_value)
end
end
end
and then used as:
%{a: 1, b: 2}
|> X.run_if(1 == 2,
Hi Riccardo,
This is an interesting proposal! Unfortunately if the value you want to
compute is expensive, then you need to fallback to the usual `if` approach.
This is also specific to maps. It may be worth considering a more general
purpose mechanism, for example:
map
|> update_if(foo
Hi everybody,
this is my first proposal so I hope I get the format right, I've already
checked in the mailing list and I haven't found similar proposals.
*Problem*
When manually constructing a map using external options or the result of a
pattern match on a struct, I often find myself in the