由于谓词适用于列表,因此我似乎很想使用 DCG。首先让我们观察一下 Prolog 中的字符串实际上是字符代码的列表:
?- X="test".
X = [116,101,115,116]
当然,这不太可读,所以让我们看看字符本身而不是它们的代码:
?- set_prolog_flag(double_quotes,chars).
yes
?- X="test".
X = [t,e,s,t]
这样更好。考虑到谓词应该描述的关系,我选择了一个描述性名称,例如 list_list_append/3。这个谓词有一个目标:一个 dcg 规则,我们称之为 list_list//2,它使用另一个 dcg,我们称之为 list//2,来实际编写列表:
list_list_appended(L1,L2,L3) :-
phrase(list_list(L1,L2),L3). % L3 is L1+L2
list([]) --> % if the list is empty ...
[]. % ... there's nothing in the list
list([X|Xs]) --> % if there's a head element ...
[X], % ... it's 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
您的示例查询:
?- 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
作为 SWI 用户,您还可以使用这个图书馆 http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/double_quotes.pl结合set_prolog_flag(double_quotes,chars).
以获得所需形式的输出。参考这个答案 https://stackoverflow.com/a/8269897/6101159了解详情。