在Prolog中检测字符串中所有长度为k的单词

5

单词是由空格或字符串的起始/结束点分隔的任何符号字符。例如:[w,o,r,d,1,' ',w,o,r,d,2]

我需要找到给定字符串中所有长度为k的单词,并将它们附加到结果字符串中(用空格分隔)。 例如,如果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].
3个回答

3

你可以编写:

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 = ' '.

kthWords/3 调用 find_word/2 找到单词,最终返回输出列表,但在结尾添加了一个 ' 'final_kthWords(L,K,Outlist)/3 的唯一作用是删除列表末尾多余的 ' ' 并返回正确的列表:

?- 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.

1
希望有人能提出更简单的解决方案……以下似乎可行。
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 - Narek Atayan

0

不使用反转的解决方案。

% 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).

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接