gpt4 book ai didi

Prolog 更改事实顺序会产生不同的结果

转载 作者:行者123 更新时间:2023-12-03 20:20:24 25 4
gpt4 key购买 nike

Prolog 的新手。我有一个无法解释的小故障,但如果我添加其他字典(X)事实,该程序似乎可以工作。该程序采用一个字符串列表,其中的字母已被编码并生成一个解码列表。每个字母代表单词列表中的一个不同字母。所以 go([abccd,edfgh,ade,ifb,kdl],X) 返回 X = ['HELLO', 'WORLD', 'HOW', 'ARE', 'YOU']。问题是如果字典('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 很酷。谢谢你的帮助。

最佳答案

我的解决方案让我明白问题是从哪里来的

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.

关于Prolog 更改事实顺序会产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30961759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com