Lists
One name can hold many values at once.
Making a list
How do we keep three fruits under one name?
In a list, written with #[ and ]:
var fruits #["apple" "pear" "plum"]
The items are separated by spaces, nothing else.
Why the #?
Because plain [apple pear plum] would be a group, and a group is a
call. The # says: this is a list of values, not something to do.
How many items does it have?
len counts:
>>> (len fruits)
3
Picking an item
How do we get the first fruit?
With its position in square brackets, touching the name. Positions start
at 0:
>>> fruits[0]
"apple"
>>> fruits[2]
"plum"
And the last one, without counting?
-1 counts from the end:
>>> fruits[-1]
"plum"
Changing a list
Can we add an item?
Every list has an append method. A method is called with a dot after
the name, inside parentheses:
>>> (fruits.append "fig")
>>> fruits
#["apple" "pear" "plum" "fig"]
append changes the list in place and shows nothing.
Is something in the list?
in asks:
>>> (in "pear" fruits)
True
>>> (in "kiwi" fruits)
False
Doing something with each item
How do we print every fruit?
for-each runs its body once per item, with the item under a name:
for-each [fruit fruits]:
print "I like" fruit
The brackets hold the name to use and the list to walk.
Can we add up a list of numbers?
sum does that in one call:
>>> (sum #[3 4 5])
12
Can we make a new list out of an old one?
list-each builds a list from the value of its body, once per item:
var prices #[3 4 5]
var doubled:
list-each [price prices]:
(* price 2)
print doubled
That prints [6, 8, 10]. prices is unchanged.
What does this print?
var scores #[7 10 4]
for-each [score scores]:
if (>= score 10):
print score "is a top score"
else:
print score "is a score"
print "best:" (max scores)
Three lines, one per score, then best: 10.