transform M dimensional list in one dimension

276 views Asked by At

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

There are 2 answers

0
Óscar López On BEST ANSWER

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)))
1
John Clements On

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.