我想将通过整数分隔的单词列表拆分为列表列表。
示例查询和预期结果:
?- separatewords([h,e,l,l,o,1,o,v,e,r,3,t,h,e,r,e], X).
X = [[h,e,l,l,o],[o,v,e,r],[t,h,e,r,e]].
我已经实现了以下几点:
将列表拆分为第一个整数之前和第一个整数之后的一个列表:
带有结果的示例查询:
?- take1word([h,e,l,l,o,1,o,v,e,r,3,t,h,e,r,e], X, Y).
X = [h,e,l,l,o], Y = [o,v,e,r,3,t,h,e,r,e]. % OK
我的代码:
take1word([H|T],[],T) :-
integer(H).
take1word([H|T],[H|Hs],Y) :-
( float(H), take1word(T,Hs,Y)
; atom(H), take1word(T,Hs,Y)
).
为了分隔单词,我的代码如下:
separatewords([],[]).
separatewords([H|T],L) :- separatewords(T,[take1word([H|T],)|L]).
它只给我
false
结果,但我不知道,我做错了什么。
最佳答案
您有问题 take1word/3
: 如果列表中有一个整数,它会取一个单词,但不会取最后一个单词。您需要向其中添加另一个基本子句:
take1word([], [], []).
take1word([H|T],[],T) :- integer(H).
take1word([H|T],[H|Hs],Y) :- float(H), take1word(T,Hs,Y); atom(H), take1word(T,Hs,Y).
现在您的
separatewords/2
将工作:separatewords([],[]).
separatewords(L, [W|T]) :- take1word(L,W,R), separatewords(R,T).
Demo.
关于list - Prolog:在列表列表中的整数处拆分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27077920/