Newsgroups: comp.lang.lisp
Path: cantaloupe.srv.cs.cmu.edu!rochester!udel!news.mathworks.com!newsfeed.internetmci.com!howland.reston.ans.net!ix.netcom.com!netcom.com!NewsWatcher!user
From: hbaker@netcom.com (Henry Baker)
Subject: Re: clever flatten?
Message-ID: <hbaker-1202960831400001@10.0.2.15>
Sender: hbaker@netcom19.netcom.com
Organization: nil organization
References: <hbaker-0902961757550001@10.0.2.15> <4fks2h$mks@sparcserver.lrz-muenchen.de> <hbaker-1102961809390001@10.0.2.15>
Date: Mon, 12 Feb 1996 16:31:40 GMT
Lines: 60

In article <hbaker-1102961809390001@10.0.2.15>, hbaker@netcom.com (Henry
Baker) wrote:

> In article <4fks2h$mks@sparcserver.lrz-muenchen.de>,
> kepser@cis.uni-muenchen.de (Stephan Kepser) wrote:
> 
> > In article <hbaker-0902961757550001@10.0.2.15> hbaker@netcom.com (Henry  
> > Baker) writes:
> > > In article <Ul6vo1C00iUvE7tL4d@andrew.cmu.edu>, "Robert G. Malkin"
> > > <rm6k+@andrew.cmu.edu> wrote:
> > > 
> > > > does anyone know of a clever list flattening routine?
> > > > that is,
> > > > (flatten '((ab) nil (a (bcd)) (df))) -> (ab a bcd df)
> > > > [ ... ]
> > > 
> > > (defun flatten (x) (flatten-helper x nil))
> > > 
> > > (defun flatten-helper (x r)      ;;; 'r' is the stuff to the 'right'.
> > >   (cond ((atom x) (cons x r))
> > >         (t (flatten-helper (car x) (flatten-helper (cdr x) r)))))
> > 
> > Could it be that you missed one obvious case in your FLATTEN-HELPER?
> > > (flatten '((a b)))
> > (A B NIL NIL)
> > 
> > 
> > (defun flatten-helper (x r)      ;;; 'r' is the stuff to the 'right'.
> >   (cond ((null x) r)
> >         ((atom x) (cons x r))
> >         (t (flatten-helper (car x) (flatten-helper (cdr x) r)))))
> > 
> > Now:
> > > (flatten '((a . b) c (d e f) ((g h) (i j))))
> > (A B C D E F G H I J)
> 
> Yes, thanks very much.  (blush, blush!)
> 
> No, I didn't get a chance to test my code, because my Coral Common Lisp
> bit the dust when I changed from System 6 to System 7 on my Mac.
> 
> I have a version of xlisp somewhere, but I thought I could at least give the
> basic idea for this homework problem.
> 
> I use the same trick for qsorting _lists_ in some of my papers in my ftp
> directory.  That code, I _did_ test!

I forgot to point out that my posted flatten is for _cons_ 'trees',
not for _list_ 'trees'.  But the poster asked for a flattener for list trees,
so this was wrong.

This flattener is cheap on the number of conses, but does not minimize
space in the stack, even after doing proper tail recursion.  If you want
a flattener which minimizes the total amount of space, then you want to
start thinking about Deutsch-Schorre-Waite.

-- 
www/ftp directory:
ftp://ftp.netcom.com/pub/hb/hbaker/home.html

