问题描述
我想在序言中创建KMP并开始这样工作。不幸的是,我无法创建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,N),!;
write('Else'),string_chars(0,P = Element,S is StartPos+1.
loop(CharatStartPos,TextLength,PrefixList):-
StartPos<TextLength,write('Start position is: '),write(StartPos),nl,compare(CharatStartPos,P),loop(CharatStartPos,!;
StartPos=TextLength,write("Loop end"),write(PrefixList).
createPrefixTable(Text,PrefixList):-
getTextAsList(Text,ListText),getTextLength(Text,TextLength),StartPos=1,NextPos=0,nth0(0,ListText,CharatStartPos),nth0(1,CharatNextPos),write(NextPos),write(CharatStartPos),write(CharatNextPos),PrefixList),write(PrefixList),write("Finish").
解决方法
您使用;
来实现析取不是习惯性的,并且是不正确的。即使;
存在,您也应该几乎总是使用单独的子句。这样可以更清楚地找出问题所在:
loop(CharAtStartPos,CharAtNextPos,StartPos,NextPos,TextLength,PrefixList):-
StartPos<TextLength,write('Start position is: '),write(StartPos),nl,compare(CharAtStartPos,PrefixList,S,N,P),loop(CharAtStartPos,P).
loop(CharAtStartPos,PrefixList):-
StartPos=TextLength,write("Loop end"),write(PrefixList).
第二个子句不以任何方式绑定PrefixList
。呼叫者将永远无法从该谓词中获取信息!
我认为您可能想添加一个“累加器”参数,该参数在递归调用上“构建”前缀列表。当递归停止时,最终结果应为累加器值。这样的东西(未经任何测试):
loop(CharAtStartPos,PrefixList0,PrefixList) :-
StartPos < TextLength,PrefixList1),PrefixList1,PrefixList).
loop(CharAtStartPos,PrefixList):-
StartPos = TextLength,write(PrefixList).
“外部”的初始调用需要传递合适的初始累加器值,例如:
loop(CharAtStartPos,[],PrefixList)