4 ms·
myvar = 5 myvar = if somepredicate() do 200 else myvar end
by Dowwie 3y ago
myvar = 5
myvar = if somepredicate() do
200
else
myvar
end
- lkuty 3y agoThe wish of the OP is to avoid writing "else myvar". You could write a macro I guess. Something like the one below. Not that I have named the macro cond_assign for conditional assignment but there is no real assignement in Elixir, it is the match operator. Here we restrict its usage to "assignment" so expr1 should be a variable. defmodule OurMacro do defmacro cond_assign(expr1, expr2, do: block) do quote do unquote(expr1) = if unquote(expr2), do: unquote(block), else: unquote(expr1) end end end iex> import OurMacro OurMacro iex> myvar = 5 5 iex> cond_assign myvar, false, do: 200 5 iex> myvar 5 iex> cond_assign myvar, true, do: 200 200 iex> myvar 200
- lkuty 3y agoHere is a better version that checks if expr1 is a variable. The condition "is_atom(x)" might be too strong. defmodule OurMacro do defmacro cond_assign(expr1, expr2, do: block) do case expr1 do {x, _, y} when is_atom(x) and is_atom(y) -> nil _ -> :erlang.error(RuntimeError.exception("The lvalue is not a variable: #{Macro.to_string(expr1)}")) end quote do unquote(expr1) = if unquote(expr2), do: unquote(block), else: unquote(expr1) end end end