Day 16 - Working with Lists
Skills: 3
Pre-reading: None
Intro (5 mins)
- Today we will continue practicing with
for eachloops.
Class Exercises (50 mins)
- Design a function
my-doublesthat takes a list of numbers and returns a new list where each element is twice what the corresponding element was in the original list. - Re-implement the same function as
my-doubles-mapusingmapfrom thelistslibrary. Which implementation do you find clearer? - Design
my-string-lens, which takes a list of strings and returns a new list where each element is the length of the string in the corresponding position in the input list. - Re-implement the same function as
my-string-lens-mapusingmapfrom thelistslibray. Which implementation do you find clearer? - Design
my-pos-nums, which takes a list of numbers and returns a new list that contains only those numbers in the original list that are positive. - Re-implement the same function as
my-pos-nums-filterusingfilterfrom thelistslibrary. Which implementation do you find clearer? - Design
my-alternating, which takes a list of any element and returns a new list that contains every other element -- i.e., keep the first, skip the second, etc. Note: you may need two mutable variables for this one -- one to contain the result, as normal, but the other to keep track of the alternation. - Can you express
my-alternatingusing eithermaporfilter? - Design
my-running-sum, that takes a list of numbers and returns a list where each position contains a sum of the numbers in the original list up to the corresponding position. i.e.,my-running-sum([list: 1, 2, 3]) is [list: 1, 3, 6]. - Can you express
my-running-sumusing eithermaporfilter?
Wrap-up (5 mins)
for eachloops are very expressive, but sometimes harder to understand than using built-in operations likefilterormap.