8

How can you add an element to the end of a list (before the empty) when only cons, first, rest, empty? and cond recursions can be used

user1718737
  • 113
  • 1
  • 1
  • 2
  • 1
    Just to note: if we disregard the artificial restrictions here of this homework assignment, then adding an element *E* to the end of the list *L* is: *(append L (list E))*. Adding to the end of a list can be expensive, so without additional context, the requested operation is something that most programmers will avoid unless the problem domain requires it, and even then, plain vanilla lists are probably not the right data structure. – dyoo Oct 04 '12 at 18:20

2 Answers2

8

Think about how you would implement append (or, more generally, think about how you would implement a right-fold). Now, if you append a list to a singleton list containing your element-to-add, you've basically appended your element.

(Obviously, this is O(n), so don't add elements individually this way.)


Here's a solution using a right-fold:

(define (append-element lst elem)
  (foldr cons (list elem) lst))

and a solution using append:

(define (append-element lst elem)
  (append lst (list elem)))

So if you can implement either foldr or append yourself, using the operations you've listed (it's easy! try it), you're good to go.

P.S. In fact, you can implement append using a right-fold:

(define (append lst1 lst2)
  (foldr cons lst2 lst1))

but that still leaves you to implement foldr yourself. ;-) (Hint: it's easy. Look at my implementation of left-fold for starting ideas.)

Community
  • 1
  • 1
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
3

This looks like homework, so I'll give you some pointers to get you right on track, fill-in the blanks:

(define (add-last lst ele)
  (cond ((empty? lst)    ; if the list is empty
         <???>)          ; create a one-element list with `ele`
        (else            ; if the list is non-empty
         (cons <???>     ; cons the first element in the list
               <???>)))) ; with the result of advancing the recursion

The above can be implemented in terms of cons, first, rest, empty? and cond, no other procedures are needed.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • I'm also learning Scheme and I want to ask you something about your answer: Does this procedure will create a new list or add the ele to the end of list lst? Thanks. – VansFannel Oct 26 '18 at 10:59
  • 1
    Most list procedures will create a new list, unless you see something like `set-car!` or `set-cdr!` in the code. – Óscar López Oct 26 '18 at 12:39