Since the predicate works on lists, I find it tempting to use DCG. First of all, pay attention to the fact that lines in Prolog are really lists of character codes:
?- X="test". X = [116,101,115,116]
Of course, this is not very readable, so let's look at the symbols themselves for their codes:
?- set_prolog_flag(double_quotes,chars). yes ?- X="test". X = [t,e,s,t]
This is better. Thinking about the relation that the predicate should describe, I choose a descriptive name, for example list_list_appended / 3. This predicate has one purpose: a dcg rule, let it call list_list // 2, which uses another dcg, call its list // 2 to actually write the lists:
list_list_appended(L1,L2,L3) :- phrase(list_list(L1,L2),L3). % L3 is L1+L2 list([]) --> % if the list is empty ... []. % ... there nothing in the list list([X|Xs]) --> % if there a head element ... [X], % ... it in the list list(Xs). % the tail is also a list list_list(L1,L2) --> % the list consists of ... list(L1), % ... L1 followed by ... list(L2). % L2
Your sample queries:
?- list_list_appended("test","auie","testauie"). yes ?- list_list_appended(L1,"auie","testauie"). L1 = [t,e,s,t] ? ; no ?- list_list_appended("test",L2,"testauie"). L2 = [a,u,i,e] ? ; no ?- list_list_appended("test","auie",L3). L3 = [t,e,s,t,a,u,i,e] ?- list_list_appended(L1,L2,"testauie"). L1 = [], L2 = [t,e,s,t,a,u,i,e] ? ; L1 = [t], L2 = [e,s,t,a,u,i,e] ? ; L1 = [t,e], L2 = [s,t,a,u,i,e] ? ; L1 = [t,e,s], L2 = [t,a,u,i,e] ? ; L1 = [t,e,s,t], L2 = [a,u,i,e] ? ; L1 = [t,e,s,t,a], L2 = [u,i,e] ? ; L1 = [t,e,s,t,a,u], L2 = [i,e] ? ; L1 = [t,e,s,t,a,u,i], L2 = [e] ? ; L1 = [t,e,s,t,a,u,i,e], L2 = [] ? ; no
As a SWI user, you can also use this library in combination with set_prolog_flag(double_quotes,chars). to get the result in the desired form. See this answer for more details.