Example: Tracing Simultaneous Recursion on Two Lists

A function uses simultaneous recursion when it consumes two lists and its recursive calls may shorten either list, or both. Three patterns cover most cases: one list shrinks while the other is passed along unchanged, both lists shrink together, or each call chooses which list to shorten. Recognising the pattern tells you which base cases your cond needs.


Consider these three Racket functions.


racket
;; (my-append lst1 lst2) produces lst1 followed by lst2
(define (my-append lst1 lst2)
  (cond [(empty? lst1) lst2]
        [else (cons (first lst1) (my-append (rest lst1) lst2))]))

;; (dot lon1 lon2) produces the dot product of two equal-length lists
(define (dot lon1 lon2)
  (cond [(empty? lon1) 0]
        [else (+ (* (first lon1) (first lon2))
                 (dot (rest lon1) (rest lon2)))]))

;; (merge lon1 lon2) merges two lists sorted in increasing order
(define (merge lon1 lon2)
  (cond [(and (empty? lon1) (empty? lon2)) empty]
        [(empty? lon1) lon2]
        [(empty? lon2) lon1]
        [(< (first lon1) (first lon2))
         (cons (first lon1) (merge (rest lon1) lon2))]
        [else (cons (first lon2) (merge lon1 (rest lon2)))]))


a) For each function, say which argument or arguments become shorter in the recursive application, and name the pattern it follows.


In my-append, only lst1 shrinks: the recursive call is on (rest lst1) while lst2 is passed unchanged. The second list simply goes along for the ride, so the function is ordinary structural recursion on lst1 and needs just one base case, (empty? lst1).


In dot, both lists shrink by one element in every call. This is lockstep recursion: the two lists are consumed in parallel, so one base case is enough as long as the lists have equal length.


In merge, each call shortens exactly one list, but which one depends on comparing the two first elements. Neither list's progress is tied to the other's, so this is the general case of simultaneous recursion.


b) Explain why merge needs separate clauses for an empty first list and an empty second list, while dot needs only one base case.


In the general case the lists run out at different times, so the function must consider every pairing of empty and nonempty. Every combination of empty and nonempty must be handled, because a missing one leads to applying first to empty.

  • Both empty: produce empty.
  • First empty, second nonempty: the remaining second list is already sorted, so produce lon2.
  • First nonempty, second empty: produce lon1.
  • Both nonempty: compare the first elements, cons the smaller one and recur on the list it came from.

The both-empty clause is technically covered by the next clause, which would return lon2, itself empty; writing it out keeps the four-way template visible. In dot the lists shrink together, so whenever lon1 is empty, lon2 is empty too, and one test settles both.


c) Trace (merge (list 2 5 9) (list 3 4)). Describe each application of merge, then give the result and the number of applications, counting the initial one.


Each application that recurs conses one element onto the result and removes that element from the list it came from.

  1. First application, with lists (list 2 5 9) and (list 3 4): since 2 < 3, cons 2 and recur on the rest of the first list.
  2. Second application, with lists (list 5 9) and (list 3 4): the test 5 < 3 is false, so cons ________ and recur with second argument ________.
  3. Third application: the test 5 < 4 is false, so cons 4 and recur; the second list is now ________.
  4. Fourth application: with nothing left in the second list, the third clause returns (list 5 9) without recurring.

Consing the chosen elements back onto that base result gives (list 2 3 4 5 9) after four applications of merge. The elements 5 and 9 were never compared with each other; the base case returned them as a block because the first list was already sorted.


d) Evaluate (dot (list 2 -1 3) (list 4 5 -2)), then explain what goes wrong if the two lists have different lengths.


Each application multiplies the two first elements and adds the dot product of the two rests.

  • First application: 2 × 4 = ________.
  • Second application: (-1) × 5 = ________.
  • Third application: 3 × (-2) = ________.
  • Fourth application: both lists are empty, so the base case produces 0.


8+(−5)+(−6)+0=−38 + (-5) + (-6) + 0 = -3


The dot product is -3, reached after four applications. Lockstep recursion relies on the lists having equal length: if lon2 were shorter, lon1 would still be nonempty when lon2 ran out, and (first lon2) would raise an error. If lon1 were shorter, the leftover elements of lon2 would be silently ignored, giving a wrong answer with no error.

A packing program receives two lists of container masses in kilograms. It adds the masses at corresponding positions and stops when either list is empty. Any unpaired containers are excluded.


The helper head(x) returns the first entry of a nonempty list, and tail(x) returns the list with its first entry removed. Complete the two replacement expressions in this function.


Python
def paired_mass(a, b):
    if not a or not b:
        return 0
    return head(a) + head(b) + paired_mass(NEXT_A, NEXT_B)


Replace NEXT_A with and replace NEXT_B with . Each expression must use the supplied helper functions and the appropriate list name.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A student writes the following function to merge two lists of numbers, each sorted in increasing order, but leaves out one of the base cases.


racket
(define (merge lon1 lon2)
  (cond [(empty? lon1) lon2]
        [(< (first lon1) (first lon2))
         (cons (first lon1) (merge (rest lon1) lon2))]
        [else (cons (first lon2) (merge lon1 (rest lon2)))]))


Which of the following applications produces an error instead of a sorted list?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

The function below merges two lists of numbers, each sorted in increasing order.


racket
(define (merge lon1 lon2)
  (cond [(and (empty? lon1) (empty? lon2)) empty]
        [(empty? lon1) lon2]
        [(empty? lon2) lon1]
        [(< (first lon1) (first lon2))
         (cons (first lon1) (merge (rest lon1) lon2))]
        [else (cons (first lon2) (merge lon1 (rest lon2)))]))


Consider the application (merge (list 1 6 8) (list 2 3 7 10)). Find the total number of applications of merge, including the initial one; the length of the list returned by the application that stops recurring; and how many elements of the result were consed from the first list before that application. Give each answer as a whole number.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors