Fill the list with a loop

Why can't I populate the list with this simple loop?

new_data = [] for data <- old_data do new_data = List.insert_at(new_data, -1, data) end 

After this operation, my new_data list is still empty, even if the loop is executed N times.

+5
source share
1 answer

In Elixir, you cannot change the value that your variable refers to, as described in Are Elixir variables immutable? . In this case, this is not a "cycle", this is a description.

You can assign the result of understanding with:

 new_data = for data <- old_data do data end 

In your line:

 new_data = List.insert_at(new_data, -1, data) 

The variable new_data is local to the realm of understanding. You can use your previous new_data value, but you cannot re-bind to the outer scope. This is why new_data is still [] after your understanding. Scoping rules are described at http://elixir-lang.readthedocs.org/en/latest/technical/scoping.html

+16
source

Source: https://habr.com/ru/post/1236447/


All Articles