Lecture 1
Lecture 2
Lecture 3
Lecture 4
Lecture 5

Flattening lists

We 'flatten' a list by removing all the square brackets around any lists it contains as elements, and around any lists that its elements contain as elements, and so on for all nested lists. For example, when we flatten the list [a,b,[c,d],[[1,2]],foo] we get the list [a,b,c,d,1,2,foo] and when we flatten the list [a,b,[[[[[[[c,d]]]]]]],[[1,2]],foo,[]] we also get [a,b,c,d,1,2,foo].

Write a predicate my_flatten(+List,?Flat) (you cannot use the name flatten because it is already defined in Prolog) that holds when the first argument List flattens to the second argument Flat. There are many ways of writing this predicate. For the moment, try to come up with one using append (the built-in version of concatenate). We will discuss a more elegant one which is not making use of append in the exercise about accumulators.


Back to the practical session of day 3.