[comp.lang.scheme] how to write append from primitives?

ted@hpkslx.mayfield.HP.COM (Ted Johnson) (05/28/91)

I was playing around with siod ("Scheme in one defun"),
but it looks like it doesn't have an append function.

How would one write append, using just car, cons, and cdr?
Since the format of cons is (cons elem list) instead of 
(cons list elem), I don't see an easy way to do this....

Thanks!

-Ted

barmar@think.com (Barry Margolin) (05/29/91)

In article <1650003@hpkslx.mayfield.HP.COM> ted@hpkslx.mayfield.HP.COM (Ted Johnson) writes:
>How would one write append, using just car, cons, and cdr?

Here's a two-argument append.  The n-argument version is left as an
exercise for the reader:

(defun append (list1 list2)
  (if (null list1)
      list2
      (cons (car list1)
	    (append (cdr list1) list2))))

Unfortunately, this isn't tail recursive.  It could be made so without too
much work, but I don't feel like doing it at the moment.
-- 
Barry Margolin, Thinking Machines Corp.

barmar@think.com
{uunet,harvard}!think!barmar

raja@copper.ucs.indiana.edu (Raja Sooriamurthi) (05/29/91)

On way would be 

(define append
  (lambda (lst1 lst2)
    (if (null? lst1)
	lst2
	(cons (car lst1)
	      (append (cdr lst1) lst2)))))

Small exercise: modify append to take the union of lst1 and lst2
(assuming that lst1 and lst2 are themselves sets -- no duplicates)

barmar@think.com (Barry Margolin) (05/29/91)

In article <1991May28.202106.23617@Think.COM> barmar@think.com writes:
>(defun append (list1 list2)

Oops, sorry for using Common Lisp syntax (but the rest works in both Scheme
and CL).  Also sorry for wasting everyone's time with this apology post,
but I suspect I'd have gotten a bunch of followups and replies pointing out
my mistake if I hadn't.

-- 
Barry Margolin, Thinking Machines Corp.

barmar@think.com
{uunet,harvard}!think!barmar