Recitation 6 — for each
Skills: 3
Reading: 5.3
Working with for each Loops
To define our own list processing functions, we need a way to do computations for each element in the list. We'll use 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 IMPLEMENTATION HERE
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
Implementing Basic Functions
Product Function
Define your own product
function that takes a list of numbers and returns their product (multiply all of them together).
fun my-product(num-list :: List<Number>) -> Number block:
# YOUR CODE HERE
where:
my-product([list: 2, 3, 4]) is 24
my-product([list: 1, 2, 3, 4, 5]) is 120
end
Length Function
Define a function my-length
that takes a list of any value and returns the number of elements in the list.
fun my-length(l :: List) -> Number block:
# YOUR CODE HERE
where:
my-length([list: "a", "b", "c"]) is 3
my-length([list: 1, 2, 3, 4, 5]) is 5
my-length([list: ]) is 0
end
Finding Maximum Values
Maximum Function
Define a function my-max
that finds the largest number in a list.
fun my-max(num-list :: List<Number>) -> Number block:
# YOUR CODE HERE
where:
my-max([list: 3, 7, 2, 9, 1]) is 9
my-max([list: 5]) is 5
my-max([list: -10, -5, -20]) is -5
end
Is there any issue with the choice of initial-value
for this problem?
Wrap-Up
What's the difference between =
and :=
in Pyret? When might you implement your own list functions instead of using built-ins?