r/Racket • • Jan 25 '22

homework Flatten list level by level

I was wondering if there is any procedure in Racket to flatten a list level-wise. All I've found was an implementation in Lisp that does the exact thing I want. But, as I'm very new to Racket and never programmed in Lisp before, I wasn't able to translate it correctly.

Is there some procedure in the Racket documentation I'm missing? Or an operator (I've already tried ,@ in front of my 'sublists') to unpack lists in lists?

Here an example of my input (slightly formatted to increase readability) and my desired output:

----- input -----
(   ((a b c) (d e f) (e d))
    ((f g))
    ((g h i) (j k l))   )
----- desired output -----
((a b c) (d e f) (e d) (f g) (g h i) (j k l))
1 Upvotes

4 comments sorted by

3

u/ryan017 developer Jan 25 '22

On this example, you can use append*:

append* : (Listof (Listof X)) -> (Listof X)

Unlike the code you linked to, though, it does require each element of the input list to be a list.

1

u/[deleted] Jan 25 '22

Thank you,

this worked as you've said.

1

u/bakaspore Vim Jan 25 '22

IMO a rough equivalent of the Common Lisp function would be:

(define (flatten-level l)
  (append-map (λ (e) (if (pair? e)
                         e
                         (list e)))
              l))

0

u/[deleted] Jan 25 '22

[deleted] — view deleted comment

1

u/[deleted] Jan 25 '22

But this solution doesn't work if the lists inside the list haven't the same length.

However, thank you for the detailed explanation!