序言:在列表列表中以整数分割列表 [英] Prolog: Split list at integer in list of lists

查看:70
本文介绍了序言:在列表列表中以整数分割列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个由整数分隔的单词列表拆分为一个列表列表.

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可以使用了:

separatewords([],[]).
separatewords(L, [W|T]) :- take1word(L,W,R), separatewords(R,T).

演示.

这篇关于序言:在列表列表中以整数分割列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆