4.62 Exercise 4.62

last-pair returns the a list containing just the last value of the input list.

The first thing we need to be aware of is that this function is not total – it will not be defined for empty lists. We need to write our matching rules carefully so that this doesn’t come up.

last-pair can be defined recursively. The base case is trivial: The last pair of a one-element list is that same list. The recursive case is also straightfoward: In an element of more than one element, the last-pair is equal to the last-pair of the cdr of that list.

We can define these rules like this:

(rule (last-pair (?x) (?x)))
(rule (last-pair (?x . ?y) ?z)
      (last-pair ?y ?z))

Note that there is no matching rule for an empty list.

I don’t believe this can be used to generate lists for which a single-element list is the last pair. This would entail generating an infinite number of possible lists ending with a given value, and while infinitely-long result sets are supported by the evaluator by way of streams, generating data points that don’t exist in any provided examples or database records is not something that the evaluator can do, as far as I’m aware.