Prolog新手。我有一个小故障,我无法解释,但如果我添加其他字典(X)事实,该程序似乎工作。该程序采用字符串列表,其中字母已被编码并产生解码列表。每个字母代表单词列表中的不同字母。所以go([abccd,edfgh,ade,ifb,kdl],X)返回X = ['HELLO','WORLD','HOW','ARE','YOU']。问题是如果字典('HOW')事实出现在字典('你')之前,那么程序会返回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很酷。谢谢你的帮助。
答案 0 :(得分:1)
我的解决方案让我从问题出来了解
go(X,Y) :-
go(X,Y,[]).
go([],[],_Dict).
go([W|Ws],[T|Ts],Dict) :-
assoc_codes(W,T,Dict,DictUpd),
go(Ws,Ts,DictUpd).
assoc_codes(W,T,Dict,DictUpd) :-
atom_codes(W, Cs),
dictionary(T),
atom_codes(T, Tcs),
upd_dict(Cs, Tcs, Dict, DictUpd).
upd_dict([], [], DictUpd, DictUpd). % done, all went well
upd_dict([C|Cs], [D|Ds], Dict, DictUpd) :-
memberchk(C-T, Dict) % if C already 'assigned', must match D
-> T = D,
upd_dict(Cs, Ds, Dict, DictUpd)
; \+ ( memberchk(X-D, Dict), X \= C ),
upd_dict(Cs, Ds, [C-D|Dict], DictUpd).
注意else分支:当C尚未被分配时,对于D必须如此。如果我们将其注释掉(即
...
; % \+ ( memberchk(X-D, Dict), X \= C ),
...
)我们遇到了您报告的问题
?- go([abccd,edfgh,ade,ifb,kdl],X).
X = ['HELLO', 'WORLD', 'HOW', 'ARE', 'HOW'] ;
X = ['HELLO', 'WORLD', 'HOW', 'ARE', 'YOU'] ;
false.
事实证明,'L'必须分配给 'c'和'g'。 取消注释测试后,我们
?- go([abccd,edfgh,ade,ifb,kdl],X).
false.
?- go([abccd,edfch,ade,ifb,kdl],X).
X = ['HELLO', 'WORLD', 'HOW', 'ARE', 'YOU'] ;
false.
答案 1 :(得分:0)
几点:
代表[abccd,edfgh,ade,ifb,kdl]作为类似的vars列表:
[[A,B,C,C,D],[E,D,F,G,H],[A,D,E],[I,F,B][K,D,L]]
并将字典存储为字母列表 e.g。
dictionary(['H','E','L','L','O']).
dictionary('['W','O','R','L','D']).
然后使用Prolog回溯来匹配所有单词:
solve([],[]).
solve([Word|Ps],[Word|Words]) :- dictionary(Word), solve(Ps,Words).
并使用类似
的方式拨打电话:- solve([[A,B,C,C,D],[E,D,F,G,H],[A,D,E],[I,F,B],[K,D,L]], Answer).
请注意,这仍有相同的错误&#39;你的代码有 - 没有检查所有的vars匹配不同的字母 - 你必须编写代码...