在 Prolog 中查找每个 X 列表的程序 [英] Program to find every list of X in Prolog
本文介绍了在 Prolog 中查找每个 X 列表的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开始学习 Prolog.该程序尝试获取给定元素的所有出现次数:
I am starting on learning Prolog. This program tries to get all occurrences of a given element:
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).
但这里是错误:
?- 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
推荐答案
除了其他人写的,考虑使用 diff/2 约束:
In addition to what others wrote, consider using the dif/2 constraint:
occurrences(_, [], []).
occurrences(X, [X|Ls], [X|Rest]) :-
occurrences(X, Ls, Rest).
occurrences(X, [L|Ls], Rest) :-
dif(X, L),
occurrences(X, Ls, Rest).
您现在可以在所有方向上使用谓词,例如:
You can now use the predicate in all directions, for example:
?- 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.
最后一个解决方案意味着如果 X 与 a
和 b
都不同,则出现列表为空.
The last solution means that the list of occurrences is empty if X is different from both a
and b
.
这篇关于在 Prolog 中查找每个 X 列表的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文