Prolog:在列表列表中以整数拆分列表 [英] Prolog: Split list at integer in list of lists
问题描述
我想将通过整数分隔的单词列表拆分为列表列表.
I would like to split a list of words separated through integers into a list of lists.
示例查询和预期结果:
?- 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]].
我已经实现了以下几点:将列表拆分为第一个整数之前的一个列表和第一个整数之后的一个列表:
The following things I already achieved: Splitting the list into one list before the first integer and one after the first integer:
带有结果的示例查询:
?- 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)
).
为了分隔单词,我的代码如下:
For separating words my code is the following:
separatewords([],[]).
separatewords([H|T],L) :- separatewords(T,[take1word([H|T],)|L]).
它只给我 false
结果,但我不知道,我做错了什么.
It only give me false
as a result, but I don't know, what I am doing wrong.
推荐答案
take1word/3
有问题:如果列表中有整数,它会占用一个单词,但它会不说最后一句话.您需要为其添加另一个基本子句:
You have an issue with take1word/3
: it will take a word if there is an integer in the list, but it will not take the last word. You need to add another base clause to it:
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
可以工作了:
Now your separatewords/2
will work:
separatewords([],[]).
separatewords(L, [W|T]) :- take1word(L,W,R), separatewords(R,T).
这篇关于Prolog:在列表列表中以整数拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!