This chapter illustrates the use of cons
to build lists in a recursive way. It’s using rember
as an example.
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.
- It compares the current element to the one we’re looking for
- If the current element is the one we’re looking for it returns the rest of the list
(crd lat)
- done - 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))
firsts
takes list of lists as an argument. It returns the first element (S-expression) of each of those lists.
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
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.
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)