Functional conditions

I noticed in the 1.7.4 version the condition IF to handle its own scope, and it does not allow to persist the variable inside and neither do modifications of variables, I wonder why this change

Example:
Input:
a = 23
if true, do: a = 4
Output:
a = 23

I wonder if there is any documentation about this

1 Like
a = 23
if(true, do: a = 4)
warning: variable "a" is unused

Note variables defined inside case, cond, fn, if and similar do not leak. If you want to conditionally override an existing variable "a", you will have to explicitly return the variable. For example:

    if some_condition? do
      atom = :one
    else
      atom = :two
    end

should be written as

    atom =
      if some_condition? do
        :one
      else
        :two
      end

Unused variable found at:

https://github.com/elixir-lang/elixir/issues/7403#issuecomment-368902698

https://github.com/elixir-lang/elixir/blob/v1.7/CHANGELOG.md

[Kernel] Raise on unsafe variables in order to allow us to better track unused variable

https://github.com/elixir-lang/elixir/releases/tag/v1.7.0

[Kernel] Raise on unsafe variables in order to allow us to better track unused variables (also known as imperative assignment / variable leakage)

5 Likes

Thanks

As a side note: It is always possible to refactor such ‘assignments from within if-statements’ code to more functional code by assigning the outcome of the if-statement to something:

2 Likes