1
votes

How to define function which returns the middle element of list, assuming an odd number of elements?

(all-but-last list) returns all but the last element of list; (middle list) returns the middle element of list

to make use of "cdr" and "all-but-last" for the definition of “middle.”

1
Try to ask question by showing what you have done so far rather asking "how to ..." or "where to ..." And take a look at How do I ask a good question?nayem

1 Answers

1
votes

This is a probably a homework question which expects you to solve the problem recursively. You should try to distinguish the base cases of the recursion to build up the general definition of middle. Also, we stick to the problem and assume there is always an odd number of elements in the input list.

So first, what is the middle of a list with a single element ?

Then, given that you have to use cdr and all-but-last as basic constructs, try to define the problems using those constructs for the general case. How can you reduce the problem into recursive sub-problems using those constructs? How do you combine the recursive results to make a result?

For example, try with the next odd-sized list, a list of 3 elements and try to see how you could find the middle element using your basic construct and a recursive call.

Consider a list with elements a, e0, e1, ..., en, z. Then the middle of this list is the same as the middle of the list e0, e1, ..., en, namely the list with the first and last elements removed.

You could start with something like this, and fill the blanks:

(defun middle (list)
  (if (endp (cdr list))
      ...
      (middle ...)))