【发布时间】:2015-06-21 06:06:58
【问题描述】:
Prolog 的新手。我有一个无法解释的小故障,但如果我添加其他字典(X)事实,该程序似乎可以工作。该程序采用一个字符串列表,其中字母已被编码并生成一个解码列表。每个字母代表单词列表中的不同字母。所以 go([abccd,edfgh,ade,ifb,kdl],X) 返回 X = ['HELLO', 'WORLD', 'HOW', 'ARE', 'YOU']。问题是如果 dictionary('HOW') 事实出现在 dictionary('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!但是 name/2 已被弃用和过时了 3 多年 - 只有当您穿着 1970 年代的 2 英寸高原鞋时,您才能使用它。
标签: prolog