foo*_*oty 4 recursion runtime-error prolog prolog-dif
我开始学习Prolog.该程序试图获取给定元素的所有出现:
occurences(_, [], Res):- Res is [].
occurences(X, [X|T], Res):-
occurences(X,T,TMP),
Res is [X,TMP].
occurences(X, [_|T], Res):- occurences(X,T,Res).
Run Code Online (Sandbox Code Playgroud)
但这是错误:
?- occurences(a,[a,b,c,a],Res).
ERROR: is/2: Arithmetic: `[]/0' is not a function
^ Exception: (11) _G525 is [] ? creep
Exception: (10) occurences(a, [], _G524) ? creep
Exception: (9) occurences(a, [a], _G524) ? creep
Exception: (8) occurences(a, [c, a], _G524) ? creep
Exception: (7) occurences(a, [b, c, a], _G524) ? creep
Exception: (6) occurences(a, [a, b, c, a], _G400) ? creep
Run Code Online (Sandbox Code Playgroud)
除了其他人写的内容之外,请考虑使用dif/2约束:
occurrences(_, [], []).
occurrences(X, [X|Ls], [X|Rest]) :-
occurrences(X, Ls, Rest).
occurrences(X, [L|Ls], Rest) :-
dif(X, L),
occurrences(X, Ls, Rest).
Run Code Online (Sandbox Code Playgroud)
您现在可以在所有方向上使用谓词,例如:
?- occurrences(X, [a,a,b], Os).
X = a,
Os = [a, a] ;
X = b,
Os = [b] ;
Os = [],
dif(X, b),
dif(X, a),
dif(X, a) ;
false.
Run Code Online (Sandbox Code Playgroud)
最后的解决方案是指出现的列表是空的,如果X是从两个不同的a和b.