d0m1n1c
d0m1n1c

Reputation: 157

Scheme, how do you append a list with a single item?

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.

Upvotes: 0

Views: 6343

Answers (2)

Sylwester
Sylwester

Reputation: 48775

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)))

Upvotes: 2

Óscar López
Óscar López

Reputation: 236150

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

Upvotes: 2

Related Questions