Skip to main content

Day 16 - Working with Lists

Skills: 3

Pre-reading: None

Intro (5 mins)

  • Today we will continue practicing with for each loops.

Class Exercises (50 mins)

  • Design a function my-doubles that 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-map using map from the lists library. 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-map using map from the lists libray. 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-filter using filter from the lists library. 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-alternating using either map or filter?
  • Design my-running-sum, that takes a list of numbers and returns a list where each position conta a sum of the numbers in the original list up the corresponding position. i.e., my-running-sum([list: 1, 2, 3]) is [list: 1, 3, 6].
  • Can you express my-running-sum using either map or filter?

Wrap-up (5 mins)

  • for each loops are very expressive, but sometimes harder to understand than using built-in operations like filter or map.