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).
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).
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]).