Elixir basics · Lesson 04 (open contents)
Build a new list
Bind a list, transform it with `for`, and leave the original value unchanged.
Build a new list and keep the old one
for returns a new list. It does not edit numbers.
# Draw each value from numbers and collect a doubled value
numbers = [1, 2, 3]
doubled = for value <- numbers do
value * 2
end
# Return both lists and check the original
{numbers, doubled, numbers == [1, 2, 3]}doubledis[2, 4, 6].numbersis still[1, 2, 3].- The final result is
{[1, 2, 3], [2, 4, 6], true}.
Read from the first line down
numbers = [1, 2, 3]binds the original list to a name.value <- numbersdraws 1, then 2, then 3. The body calculates a result for each value.- The comprehension collects those results in
[2, 4, 6]. It never changes the original list.
Symbols are not secret signs
=Bind the value on the right to the name on the left. The next lesson shows its matching job.
<-Take each value from the collection on the right, one at a time.
for ... do ... endRun the body for each drawn value and collect the results in a new list.
==Compare two values and return true or false.
Match each name to its meaning
binding
Giving a value a name, as in numbers = [1, 2, 3].
immutable
An existing value is not changed in place. A transformation creates a new value.
list comprehension
A for expression that visits values and collects a new list of results.
Why these forms are useful
A binding gives a value a name. In numbers = [1, 2, 3], the name numbers points to that list.
Elixir data is immutable: code does not change the existing list in place. A transformation builds a new list instead.
A for comprehension runs one expression for each value it draws from a collection. In value <- numbers, read <- as “take each value from numbers.”
Close the answer and try
Use a for comprehension to multiply every value in [1, 2, 3] by 3. Return both the old and new lists.
numbers = [1, 2, 3]
tripled = for value ____ numbers do
____
end
{numbers, tripled}Target result: The result should be {[1, 2, 3], [3, 6, 9]}.
Stuck? Read one hint
Draw values with <-, then calculate value * 3 in the body.
After you run it, see one answer
# Build a new list from the old one
numbers = [1, 2, 3]
tripled = for value <- numbers do
value * 3
end
{numbers, tripled}Think about it: After `doubled = for value <- numbers do value * 2 end`, did `numbers` change?
No. The comprehension built a new list and bound it to doubled. The original list stayed the same.
Remember these three lines
- 1
A binding gives a value a name.
- 2
value <- listdraws each value from a list. - 3
A
forcomprehension builds a new list instead of changing the old one.