正如@false 已经指出的那样,[ ] 不是空格而是空列表。此外,您的谓词将L 描述为Head 减去空列表,并且它不关心递归的结果(deleteAll(Tail,_))。这就是为什么您会得到未更改的第一个列表作为结果。
想想谓词应该描述什么:两个列表列表之间的关系,其中第二个列表包含第一个列表的子列表,没有空格,除了最后一个未更改的子列表:
:- set_prolog_flag(double_quotes, chars).
lists_withoutspace([X],[X]). % last list unaltered
lists_withoutspace([H1,H2|T1],[H1WoS|T2]) :- % H1Wos:
list_withoutspace(H1,H1WoS), % first sublist without spaces
lists_withoutspace([H2|T1],T2). % the same for the rests
对于 list_withoutspace/2,您可以使用 te 内置谓词 char_type/2 来确定第一个列表元素的类型:
list_withoutspace([],[]). % empty list contains no space
list_withoutspace([X|T],L) :- % X is not in the list
char_type(X,space), % if it is space
list_withoutspace(T,L). % relation must also hold for tail
list_withoutspace([X|T],[X|L]) :- % X is in the list
char_type(X,alpha), % if it is a letter
list_withoutspace(T,L). % relation must also hold for tail
如果您想匹配多个字母,请相应更改alpha。如果你查询这个谓词,你会得到想要的结果:
?- lists_withoutspace([[q,' ',w,' ',e,' ',r,' ',t,' ',z],[a,' ',s,' ',d,' ',f,' ',g,' ',h],[y,' ',x,' ',c,' ',v,' ',b,' ',n]],L).
L = [[q,w,e,r,t,z],[a,s,d,f,g,h],[y,' ',x,' ',c,' ',v,' ',b,' ',n]] ? ;
no
或者更简洁:
?- lists_withoutspace(["q w e r t z","a s d f g h","y x c v b n"],L).
L = [[q,w,e,r,t,z],[a,s,d,f,g,h],[y,' ',x,' ',c,' ',v,' ',b,' ',n]] ? ;
no