1

How can i combine all of the list elements from list in lists?

example

combine([[a,b,c],[d,[e,f],g],h],X).
return X = [a,b,c,d,e,f,g,h]

This is what i had try

flat([], []).
flat([First|Rest], _X):-
    flat(Rest, First).
false
  • 10,264
  • 13
  • 101
  • 209
Jack Wong
  • 79
  • 1
  • 12
  • 1
    You can also look for inspiration at the SWI-Prolog library implementation of `flatten/2`, which is the exact predicate that you are trying to implement: http://www.swi-prolog.org/pldoc/doc/home/vnc/prolog/lib/swipl/library/lists.pl?show=src (search the page for the definition of flatten) –  Jun 06 '13 at 07:59
  • Isn't this just what the built-in `flatten` does? – lurker Jun 08 '13 at 22:56

1 Answers1

0

Recursively.

Define your base cases first - if you have no lists to combine you have an empty list.

combine([],[]).

and if you have a single element you have a singleton list

combine(X,[X]).

Then we define the general case - a non-empty list

combine([X|Xs], Y) :-

First we want to recursively flatten the head

combine(X,XX),

then the tail

combine(XS,XXs),

then we put these together

append(XX,XXs,Y).

We have to think carefully about how we put this together. The base case for the singleton element wants to appear last. When matching rules Prolog will match the first that applies - the base case with a singleton element will match a list, so we put this after this case to stop it matching in this case. Finally giving us:

combine([],[]).
combine([X|Xs],Y) :- combine(X,XX), combine(Xs,XXs), append(XX,XXs,Y).
combine(X,[X]).
selig
  • 4,834
  • 1
  • 20
  • 37