3 ms·
I wish that elixir had some syntax to simplify variable rebinding when returning from an if statement (as opposed to an if else). For example, some way to say l
by anonymousDan 3y ago
I wish that elixir had some syntax to simplify variable rebinding when returning from an if statement (as opposed to an if else). For example, some way to say leave the variable unchanged if the if statement is false instead of having to clutter up the program with one line else clauses.
Eg.
myvar = 5
myvar = if somepredicate() do
200
end
Will currently assign None to myvar if somepredicate is false.
- phanimahesh 3y agoI prefer explicit readability. Alternatives I can think of are unappealing.
- Dowwie 3y agomyvar = 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
- jonnycat 3y agoThere are a couple of options to simplify and emulate a ternary operator: if x, do: y, else: z Or, though it's not very idiomatic Elixir, this also works: x && y || z
- te_chris 3y agoThe binary matching is relatively idiomatic in liveview - check the CoreComponents files.
- peoplefromibiza 3y agoif you're writing Elixir code you'll find that most of the times the assignment is close to where you need the variable, so you usually end up writing something along the line of var = if x, do: 200, else: 5