我想在 prolog 中创建 KMP 并开始像这样工作。不幸的是,我无法创建 Prolog 所需的前缀表?考虑到 prolog 是一种逻辑语言,我做得对吗?
compare(CharAtStartPos,CharAtNextPos,StartPos,NextPos,PrefixList,S,N,P):-
CharAtStartPos=CharAtNextPos,write('Equal'),
N is NextPos+1,
string_chars(N,Element),
write("Element is"), write(Element),
S is StartPos+1,!;
CharAtStartPos\=CharAtNextPos,NextPos\=0,write('Not equal'),
value is NextPos-1,
nth0(value,PrefixList, N),!;
write('Else'),
string_chars(0,Element),
P = Element,write("Element is"),
write(Element),
S is StartPos+1.
loop(CharAtStartPos,CharAtNextPos,StartPos,NextPos,TextLength,PrefixList):-
StartPos<TextLength,
write('Start position is: '),write(StartPos),nl,
compare(CharAtStartPos,CharAtNextPos, StartPos,NextPos,PrefixList,S,N,P),
loop(CharAtStartPos,CharAtNextPos,S,N,TextLength,P),!;
StartPos=TextLength,
write("Loop end"),
write(PrefixList).
createPrefixTable(Text,TextLength, PrefixList):-
getTextAsList(Text,ListText),
getTextLength(Text,TextLength),
StartPos=1,NextPos=0,
nth0(0,ListText,CharAtStartPos), nth0(1,ListText,CharAtNextPos),
write(StartPos),write(NextPos),nl,
write(CharAtStartPos),write(CharAtNextPos),nl,
loop(CharAtStartPos,CharAtNextPos,StartPos, NextPos,TextLength, PrefixList),
write(PrefixList),
write("Finish").