Skip to main content

Recitation 6 -- for each

Skills: 3

Reading: 5.3

Objectives

  • Mutable variables
  • For each loops over lists
  • Implementing max, sum, by hand

I. Introduction (15 minutes)

Overview: To define our own list processing functions, we need a way to do computations for each element in the list. There are multiple ways to do that, but 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 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:
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

II. Basic Accumulator Patterns (20 minutes)

A. Implementing Product

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:
var result = 1
for each(n from num-list):
result := result * n
end
result
where:
my-product([list: 2, 3, 4]) is 24
my-product([list: 1, 2, 3, 4, 5]) is 120
end

B. Implementing Length

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:
var count = 0
for each(elt from l):
count := count + 1
end
count
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

III. Finding Maximum Values (20 minutes)

Implementing Maximum

Define a function my-max that finds the largest number in a list.

fun my-max(num-list :: List<Number>) -> Number:
var current-max = num-list.first
for each(n from num-list.rest):
when n > current-max:
current-max := n
end
end
current-max
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

Discussion: Ask, "Why do we start with the first element instead of 0?"

IV. Recap and Wrap-Up (5 minutes)

Key Points Discussion:

  • Mutable Variables: Can be declared with var and updated with :=
  • For Each Pattern: Initialize variable, loop through list updating variable, return final result
  • Accumulation: Building up a single result (sum, product, max)

Reflection Questions:

  • "What's the difference between = and := in Pyret?"
  • "When might you implement your own list functions instead of using built-ins?"