Setting value in within unless

Kindly educate me on the below and advise on the correct solution, came across this in a book.

alive = unless sender in state.alive do
[sender | state.alive]
else
state.alive
end
IO.inspect alive

or
alive = state.alive
unless sender in state.alive do
alive = [sender | state.alive]
end

IO.inspect alive

I’m not quite sure what your question is, but the second example won’t work as you expect it, as this is what we call an imperative assignment which have been deprecated for a long time and removed in 1.8.

But the most idiomatic version were to use an if here. unless with an else is often discouraged. Most often it’s just used for side effects in negative cases.

alive = if sender in state.alive, do: state.alive, else: [sender | state.alive]

Just came across what I posted in a book, I think the if is the way to go. Thanks for the education, hearing imperative assignment for the first time. I won’t forget that.

Which version was in the book? The first or the second? And which book was it?

And as I said, prior to 1.8 both versions should have printed the same, but the second should have given a warning at compile time. Since 1.8, there will be no visible effect from the inner assignment in the outer scope.

Well noted, I think it’s an earlier version. I most grateful for the education.

Release v1.7.0 · elixir-lang/elixir · GitHub

See also:

1 Like