dividing a list up to a point in prolog
-
21-12-2019 - |
Question
my_list([this,is,a,dog,.,are,tigers,wild,animals,?,the,boy,eats,mango,.]).
suppose this is a list in prolog which i want to divide in three parts that is up to three full stops and store them in variables.
how can i do that...
counthowmany(_, [], 0) :- !.
counthowmany(X, [X|Q], N) :- !, counthowmany(X, Q, N1), N is N1+1.
counthowmany(X, [_|Q], N) :- counthowmany(X, Q, N).
number_of_sentence(N) :- my_list(L),counthowmany(.,L,N).
i already counted the number of full stops in the list(my_list) now i want to divide the list up to first full stop and store it in a variable and then divide up to second full stop and store in a variable and so on.........
Solution
Your problem statement did not specify what a sequence without a dot should correspond to. I assume that this would be an invalid sentence - thus failure.
:- use_module(library(lambda)). list_splitted(Xs, Xss) :- phrase(sentences(Xss), Xs). sentences([]) --> []. sentences([Xs|Xss]) --> sentence(Xs), sentences(Xss). sentence(Xs) --> % {Xs = [_|_]}, % add this, should empty sentences not be allowed allseq(dif('.'),Xs), ['.']. % sentence(Xs) --> % allseq(\X^maplist(dif(X),['.',?]), Xs), % (['.']|[?]). allseq(_P_1, []) --> []. allseq( P_1, [C|Cs]) --> [C], {call(P_1,C)}, allseq(P_1, Cs).
OTHER TIPS
UPDATE: the code slightly simplified after @CapelliC comment.
One of the many ways to do it (another, better way - is to use DCG - definite clause grammar):
You don't really need counthowmany.
split([], []).
split(List, [Part | OtherParts]) :-
append(Part, ['.' | Rest], List),
split(Rest, OtherParts).
Let's try it:
?- my_list(List), split(List, Parts).
List = [this, is, a, dog, '.', tigers, are, wild, animals|...],
Parts = [[this, is, a, dog], [tigers, are, wild, animals], [the, boy, eats, mango]]
In this answer we define split_/2
based on splitlistIf/3
and list_memberd_t/3
:
split_(Xs, Yss) :-
splitlistIf(list_memberd_t(['?','.','!']), Xs, Yss).
Sample queries:
?- _Xs = [this,is,a,dog,'.', are,tigers,wild,animals,?, the,boy,eats,mango,'.'],
split_(_Xs, Yss).
Yss = [ [this,is,a,dog] ,[are,tigers,wild,animals] ,[the,boy,eats,mango] ].
?- split_([a,'.',b,'.'], Yss).
Yss = [[a],[b]]. % succeeds deterministically