Newsgroups: comp.lang.prolog
Path: cantaloupe.srv.cs.cmu.edu!das-news2.harvard.edu!news2.near.net!howland.reston.ans.net!gatech!news.mathworks.com!uunet!munnari.oz.au!cs.mu.OZ.AU!munta.cs.mu.OZ.AU!conway
From: conway@munta.cs.mu.OZ.AU (Thomas Charles CONWAY)
Subject: Re: Help with a function
Message-ID: <9512020.14389@mulga.cs.mu.OZ.AU>
Sender: news@cs.mu.OZ.AU (CS-Usenet)
Organization: Computer Science, University of Melbourne, Australia
References: <3ndv02$g0o@galileo.sct.edu>
Distribution: inet
Date: Sun, 30 Apr 1995 10:56:25 GMT
Lines: 37

chouston@st6000.sct.edu (Carlton Houston) writes:

>Does anyone know of an easy way to remove extra brackets from a list? In 
>other words, convert the list [[a,b],[c,d,e],[[[f]]]] to [a,b,c,d,e,f]?
>Any help will be appreciated.
>

The first thing to note is that the *extra* brackets in the first list
are not really *extra*. The first list is a list, the first element of
which is a list containing 'a' and 'b'; the second element is the list
containing the elements 'c' 'd' and 'e'; the third element is a list
which has a single element which is a list which has a single element
which is a list containing the single element 'f'. By contrast, the
second list has the six elements 'a' 'b' 'c' ... 'f'.

The operation to convert the first list to the second is usually called
`flattening'. There are two basic ways to do this: to keep a list of
the elments gathered so far and to append new elements onto the end
as we get them or to build up the list backwards with an accumulator.
The first method uses less stack space, but is much slower because of
all the append operations, the second uses more stack space, but avoids
the appends.

The basic way to get elements is to traverse the list. For each
element, if it is '[]' then discard it, if it is '[A|As]' then
recursively process A then all of As. If it is neither of the
above, then add it to the elements for the final list (using the
appends or an accumulator).

Of course, this program will be ill-typed by most type systems
based on the idea of many-sorted types (such as those used by
Goedel and Mercury as well as most modern functional languages).
This doesn't worry Prolog, since everything in Prolog can be
viewed as having the type 'term' (just like everything in lisp
is an S-expression).

Thomas
