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.