This is not really true, right? We aren’t using the return value of the if
block.
As I said the else is implied
Whenever you assign to a variable inside if
, you actually return it, although not in the usual sense, but implicitly via scope.
1 Like
Just for fun, I built this.
defmodule ImplicitElse do
defmacro ifeq(x, eq_value \\ nil, do: block) do
quote do
if unquote(x) == unquote(eq_value) do
unquote(block)
else
unquote(x)
end
end
end
def ifnil(x, do: block) do
ifeq(x, nil, do: block)
end
def ifzero(x, do: block) do
ifeq(x, 0, do: block)
end
end
import ImplicitElse
x = nil
x = ifnil x, do: 10
# x now is 10
x = ifnil x, do: 99
# x still is 10
2 Likes
Or if you want to be really evil, you can use an unhygienic macro, and override an operator. (disclaimer: If you use this in production code, your coworkers will probably lynch you in your sleep)
defmodule ImplicitElse do
defmacro x <<~ default do
quote do
var!(unquote(x)) =
if unquote(x) == nil do
unquote(default)
else
unquote(x)
end
end
end
end
import ImplicitElse
bar = nil
bar <<~ 42
# now bar is 42
bar <<~ 33
# bar still is 42
3 Likes
That is beautifully evil indeed, hadn’t thought of that. ^.^
1 Like