0

So far I have

(define insert-3
  (lambda (sym ls)
    (cond
      [(null? ls) '()]
      [else (cons sym (insert-3 (caadr ls)))])))

I know the caadr is wrong, because it doesn't exist in a two element list. But I don't know how to add a symbol to the end of a list.

uselpa
  • 18,732
  • 2
  • 34
  • 52

2 Answers2

0

Assuming

sym is 'c
ls  is '(a b)

then your result would be constructed by

> (cons 'a (cons 'b (list 'c)))
'(a b c)

or the equivalent

> (cons 'a (cons 'b (cons 'c null)))
'(a b c)

So your procedure needs to cons each element until it has consumed ls, and then cons (list sym) or (cons sym null) at that point:

(define insert-3 
  (lambda (sym ls) 
    (cond 
      [(null? ls) (list sym)] 
      [else       (cons (car ls) (insert-3 sym (cdr ls)))])))

such that

   (insert-3 'c '(a b))
=> (cons 'a (insert-3 'c '(b)))
=> (cons 'a (cons 'b (insert-3 'c '())))
=> (cons 'a (cons 'b (list 'c)))

which will work for any length of list:

> (insert-3 'c '(a b))
'(a b c)
> (insert-3 'e '(a b c d))
'(a b c d e)
uselpa
  • 18,732
  • 2
  • 34
  • 52
0

Here is a very simple function:

(define (insert-3 sym lst)
  (reverse (cons sym (reverse lst))))

Here is another

(define (insert-3 sym lst)
  (assert (= 2 (length lst)))
  (let ((frst (car  lst))
        (scnd (cadr lst)))
    (list frst scnd sym)))

If you want to start thinking about recursion, with a little bit of efficiency too:

(define (insert-at-end! sym lst)
  (if (null? lst)
      (list sym)
      (let looking ((l lst))
        (if (null? (cdr l))
            (begin (set-cdr! l (list sym))  ;; replace last `cdr`
                   lst)                     ;; return modified `lst`
            (looking (cdr l))))))
> (insert-at-end! 1 '(5 4 3 2))
(5 4 3 2 1)
> (insert-at-end! 1 '(2))
(2 1)
> (insert-at-end! 1 '())
(1)
GoZoner
  • 67,920
  • 20
  • 95
  • 145