Day 14 - Variables and loops
Skills: 3
Pre-reading: DRAFT:9.1.8.5 (except 9.1.8.5.4)
Intro (15 mins)
- To define our own list processing functions, we need a way to do computations
for each element in the list. Multiple ways to do that, today we will show
iteration with
for each()
. - This requires being able to modify variables, which in Pyret means they must
be declared with
var
, and must be updated with the special operator:=
. - Pattern is:
var my-var = initial-value
for each(my-elt from my-list):
code
to
handle
my-elt
and update
my-var
end
my-var # final result - Example: while
sum
is built in, we could have defined it ourselves as:fun my-sum(num-list :: List<Number>) -> Number block:
var total = 0
for each(n from num-list):
total := total + n
end
total
where:
my-sum([list: 0, 1, 2, 3]) is 6
end
Class Exercises (40 mins)
- Define your own
product
function that takes a list of numbers and returns their product (multiply all of them together). - Define a function
sum-even-numbers
that takes a list of integers and adds up only the even numbers -- the rest should be ignored (num-modulo
may be helpful)! - Define a function
my-length
that takes a list of any value and returns the number of elements in the list.
TODO / FIXME ADD MORE
Wrap-up (5 mins)
- Mutable variables can be declared with
var
and updated with:=
. for each
can run code for each element of a list; combined with mutable variables, this allows writing custom list operations.