Frage

I'm trying to make a function to append a list with a single item. What it's doing though is returning a dot pair.

(define (append lst x)
  (cond
    ((null? lst) x)
    (else (cons (car lst) (append (cdr lst) x)))))

The output I'm getting is

> (append '(1 2 3 4 5 6 7) 8)
(1 2 3 4 5 6 7 . 8)

I'm trying to get

(1 2 3 4 5 6 7 8)

Thanks.

War es hilfreich?

Lösung

Try this:

(define (append lst x)
  (cond
    ((null? lst) (cons x '())) ; here's the change
    (else (cons (car lst) (append (cdr lst) x)))))

Notice that all proper lists must end in the empty list, otherwise it'll happen what you just experienced. To put it in another way:

(cons 1 (cons 2 3))
=> '(1 2 . 3) ; an improper list

(cons 1 (cons 2 (cons 3 '())))
=> '(1 2 3)   ; a proper list

Andere Tipps

If you are allowed to use append there is no reason why not. It performs pretty much the same as what you are trying since append is O(n) where n is the number of elements in the first list. This is just less code.

;; append element to last
(define (append-elt lst x)
  (append lst (list x)))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top