Task

Write a function to flatten the nesting in an arbitrary list of values.

Your program should work on the equivalent of this list:

  [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]

Where the correct result would be the list:

   [1, 2, 3, 4, 5, 6, 7, 8]

Related task

   Tree traversal


:- module flatten_a_list.
:- interface.
 
:- import_module io.
 
:- pred main(io::di, io::uo) is det.
 
:- implementation.
 
:- import_module list.
 
:- type tree(T)
    --->    leaf(T)
    ;       node(list(tree(T))).
 
:- func flatten(tree(T)) = list(T).
 
flatten(leaf(X)) = [X].
flatten(node(Xs)) = condense(map(flatten, Xs)).
 
main(!IO) :-
    List = node([
        node([leaf(1)]),
        leaf(2),
        node([node([leaf(3), leaf(4)]), leaf(5)]),
        node([node([node([])])]),
        node([node([node([leaf(6)])])]),
        leaf(7),
        leaf(8),
        node([])
    ]),
    io.print_line(flatten(List), !IO).
 
:- end_module flatten_a_list.
 