Skip to content

Latest commit

 

History

History
42 lines (25 loc) · 1.85 KB

File metadata and controls

42 lines (25 loc) · 1.85 KB

03

This chapter illustrates the use of cons to build lists in a recursive way. It’s using rember as an example.

Explain rember in your own words

rember (see 03.rkt) is a function that removes the first occurrence of a given element from a given list. It does it by going through each and every item on the given list.

  1. It compares the current element to the one we’re looking for
  2. If the current element is the one we’re looking for it returns the rest of the list (crd lat) - done
  3. If the current element is not the one we’re looking for: 4. It builds a new list and keeps the current element (cons (car lat) … ) 5. It recurs with the rest of the list (rember a (cdr lat))

Explain firsts function

firsts takes list of lists as an argument. It returns the first element (S-expression) of each of those lists.

Third commandment

When building a list, describe the first typical element, and then cons it onto the natural recursion.

Or in other words your else statement is usually made of:

  • selector for the element you want to put into the list
  • recursive call for traversing the function

‌(cons (first (first los)) (firsts (rest los)))

…in case of natural recursion

insertR

inseertR takes two atoms (new, old) and a list of atoms (lat) as in input. It builds a new list. It looks up the old item and replaces it with the new + old.

The preliminary Fourth commandment

Always change at least one argument when recurring, usually it’s passing a crd of an input list back to the function. This way we make sure that there’s always at least one element less to go iterate over per function run. Otherwise we would:

  • constantly cycle through the same list (process running forever)
  • add more items to the input list per function run (sooner or later this will exhaust the memory)