對序言不熟悉。我有一個我無法解釋的小故障,但是如果我添加其他字典(X)事實,該程序似乎工作。該程序需要一個字符串列表,其中的字母已經被編碼併產生一個解碼列表。每個字母表示單詞列表中的不同字母。所以去([abccd,edfgh,ade,ifb,kdl],X)返回X = ['HELLO','WORLD','HOW','ARE','你']。問題是如果字典('HOW')事實出現在字典('YOU')事實之前,那麼程序返回X = ['HELLO','WORLD','HOW','ARE','HOW']。 。這裏是令人毛骨悚然的代碼:事實的序言更改順序產生不同的結果
/*word bank*/
dictionary('HELLO').
dictionary('WORLD').
dictionary('HOW').
dictionary('ARE').
dictionary('YOU').
/*This spits out a single list where
the lengths of words in the dictionary
are matched to each word in the encoded
message, so [abccd,edfgh,ade,ifb,kdl]
matches [HELLO,WORLD,HOW,ARE,HOW] or
any combination*/
sameLength([X|XTail],[Y|YTail]) :-
dictionary(Y),
name(X,L1),name(Y,L2),
length(L1,Z),length(L2,Z),
sameLength(XTail,YTail).
sameLength([],[]).
/*Turns a list of lists into
a single list*/
oneWord([X|XTail],Y) :-
name(X,L),
append(L,Z,Y),
oneWord(XTail,Z).
oneWord([],[]).
/*This replaces the letters that are in
the dictionary, with the letters in the
message. If at any point a letter has
been replaced because it is UPPERCASE,
and that letter is being replaced by
something else then fail, other wise,
the letter has to be lowercase*/
replaceLetters(List,[X|XTail],[Y|YTail],Result) :-
(X<91,X=Y);(X>96),
replaceP(X,Y,List,Result1),
replaceLetters(Result1,XTail,YTail,Result).
replaceLetters(Result,[],[],Result).
/*the call to action*/
go(X,Y) :-
sameLength(X,Y),
oneWord(X,A),
oneWord(Y,B),
replaceLetters(A,A,B,C),
B=C,
!.
/*replace thanks to @repeat*/
replaceP(_, _, [], []).
replaceP(O, R, [O|T], [R|T2]) :- replaceP(O, R, T, T2).
replaceP(O, R, [H|T], [H|T2]) :- dif(H,O), replaceP(O, R, T, T2).
我想補充一點,Prolog很酷。謝謝你的幫助。
+1使用dif/2!但是名稱/ 2自30多年以來已被棄用和過時 - 如果您從20世紀70年代開始穿2英寸高原鞋,則只允許使用它。 – false