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:

elixir/CHANGELOG.md at v1.7 · elixir-lang/elixir · GitHub

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

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

[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