Detect all words of string length k in prolog

Words are any character characters separated by spaces or the start / end points of a string. E.g. [w,o,r,d,1,' ',w,o,r,d,2] .

I need to find all the words of length k of the given string and add them to the result line (separated by spaces). This is what I expect, for example, in the case of k = 5:

 ?- kthWords([w,o,r,d,1,'',w,r,d,'',w,o,r,d,2], 5, X). X = [w,o,r,d,1,'',w,o,r,d,2]. 
+5
source share
3 answers

You can write:

 final_kthWords(L,K,Outlist):- kthWords(L,K,L1), reverse(L1,[_|T]), reverse(T,Outlist). kthWords([],_,[]):-!. kthWords(L,K,L1):- find_word(L,Word,L2), length(Word,N), (N=:=K-> append(Word,[' '|T],L1),kthWords(L2,K,T); kthWords(L2,K,L1)). find_word([],[],[]). find_word([H|T],[H|T1],L):-dif(H,' '),find_word(T,T1,L). find_word([H|T],[],T):- H = ' '. 

Where kthWords/3 calls find_word/2 , which finds the words, and finally kthWords returns an output list, but adds in the end. ' ' The only thing final_kthWords(L,K,Outlist)/3 does is remove the extra ' ' at the end of the list and return the correct list:

 ?- final_kthWords([w,o,r,d,1,' ',w,r,d,' ',w,o,r,d,2], 5, X). X = [w, o, r, d, 1, ' ', w, o, r, d, 2] ; false. 
+3
source

Hoping someone else can offer a simpler solution ... it seems to work

 kthWordsH([], 0, _, R0, R0). kthWordsH([], N, _, _, []) :- N \= 0. kthWordsH([' ' | Tl], 0, Len, W, Revult) :- kthWordsH(Tl, Len, Len, [], Res0), append(Res0, [' ' | W], Revult). kthWordsH([' ' | Tl], N, Len, _, Revult) :- N \= 0, kthWordsH(Tl, Len, Len, [], Revult). kthWordsH([H | Tl], 0, Len, _, Revult) :- H \= ' ', kthWordsH(Tl, Len, Len, [], Revult). kthWordsH([H | Tl], N, Len, Tw, Revult) :- H \= ' ', N \= 0, Nm1 is N-1, kthWordsH(Tl, Nm1, Len, [H | Tw], Revult). kthWords(List, Len, Result) :- kthWordsH(List, Len, Len, [], Revult), reverse(Revult, Result). 
+1
source

The solution is without reverse.

 % return a word of k length, or return [] otherwise kword(K,L,W):- length(L,K) -> append(L,[' '],W); W=[]. % if no more chars, then check final word in L and % append to word list Ls to return Lw kwords(K,[],L,Ls,Lw):- kword(K,L,W), append(Ls,W,Lw). % if char is space, then append to Ls if word of length K % if not space, append char to "in progress" work list L kwords(K,[C|Cs],L,Ls,Lw):- ( C=' ' -> ( kword(K,L,W), append(Ls,W,Ls0), L2 = [] ); ( append(L,[C],L2), Ls0 = Ls ) ), kwords(K,Cs,L2,Ls0,Lw). % intialise predicate call with empty word and empty result kthWords(Cs,K,L):- kwords(K,Cs,[],[],L). 
0
source

Source: https://habr.com/ru/post/1258672/


All Articles