1

I'm new in scheme programming and I'm learning basic algorithms, like how to define map, append and so on.

But there is an algorithm for which I can't find an implementation. I speak about transforming an M-dimensional list into one dimension. I tried to define it by myself, but without success.

What exactly I want:

'(a b c (d (e)) (g f h)) => '(a b c d e g f h)
Óscar López
  • 232,561
  • 37
  • 312
  • 386

2 Answers2

2

I think the term you want to search for is "Flatten". The simplest way to write it is this: if it's not a list, then return a list of length one containing it. If it is a list, then apply append to the result of mapping a recursive call over its elements.

John Clements
  • 16,895
  • 3
  • 37
  • 52
  • 1
    **flatten** is built-into Racket's standard library: http://docs.racket-lang.org/reference/pairs.html#(def._((lib._racket/list..rkt)._flatten)) – dyoo Feb 21 '12 at 20:59
1

There are a couple of ways to flatten a list. First, a straightforward solution using only primitive list procedures:

(define (flatten lst)
  (cond ((null? lst)
         '())
        ((not (list? lst))
         (list lst))
        (else
         (append (flatten (car lst))
                 (flatten (cdr lst))))))

This other solution uses the map higher-order procedure and apply (as suggested by John Clements):

(define (flatten lst)
  (if (not (list? lst))
      (list lst)
      (apply append (map flatten lst))))

And finally, as has been mentioned in the comments, the built-in flatten procedure found in some Scheme implementations like Racket (I don't know if it's available in bigloo):

(require racket/list)
(flatten '(a b c (d (e)) (g f h)))
Óscar López
  • 232,561
  • 37
  • 312
  • 386