Question

I am currently attempting to resolve a question in a practice mid-term. The question asks for me to write an expression to append two lists (let us call them list1 and list2), and list2 must be appended to the end of list1. The function append cannot be used at any point in this. What I may use is cons, filter, accumulate, map, list-ref, and inumerate-interval. I have attempted various forms of getting to the solution, such as

(cons list1 list2)

(filter list? (map list (cons list1 list2)))

(list list1 list2)

(map list (list list1 list2)) 

I have spent 2 days attempting to find a solution to no avail. If anyone is able to guide me in the right direction, or even provide me with some form of assistance, I would be grateful.

Also, I apologize if there is some protocol that I am following incorrectly for the code formatting or the mannerisms in asking the question, as I am new to the site. Thank you.

Était-ce utile?

La solution

Because this is homework, I can't give you a straight answer. Instead, I'll give you some hints, you can find the answer to your own question filing-in the blanks. This is the standard way to implement append:

(define (my-append l1 l2)
  (cond (<???>                          ; if the first list is null
         <???>)                         ; then return the second list
        (<???>                          ; if the second list is null
         <???>)                         ; then return the first list
        (else                           ; otherwise `cons`
         (cons <???>                    ; the first element of the first list
               (my-append <???> l2))))) ; process the rest of the first list

The above solution uses cond, null?, cons, car and cdr. If you can't use any of those and you're restricted to the procedures in the question, try this instead (assuming accumulate is defined as a fold to the right):

(define (my-append l1 l2)
  (accumulate
   <???>   ; what should be used for sticking list elements together?
   <???>   ; what should we return if the list being traversed is empty?
   <???>)) ; this is the list that we want to traverse 

The above solution only uses accumulate and cons, as requested in the question. The idea is: traverse the first list recreating it element by element, until the list is exhausted - at that point, the next element will be the second list.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top