[英]Delete predicates from the list in Prolog
I want to delete all predicates named a
from the list.我想从列表中删除所有名为a
的谓词。 The result must be as shown below:结果必须如下图所示:
?- delete_all(a(_), [a(1),a(2),a(3),b(1)], R).
R = [b(1)]
Please, do not offer me built in solutions of SWI or others, because the code must be in Amzi-Prolog.请不要向我提供 SWI 或其他内置解决方案,因为代码必须在 Amzi-Prolog 中。
Thanks.谢谢。
Edit: I have tried the following code but it is working properly only for atoms:编辑:我尝试了以下代码,但它仅适用于原子:
remove_all(X,[],[]).
remove_all(X,[X|L],R):-remove_all(X,L,R).
remove_all(X,[Y|L],R):-not(X=Y), remove_all(X,L,M), R=[Y|M].
?-remove_all(a(_), [a(1),a(2),a(3),b(1)], R).
R=[a(2),a(3),b(1)]
which is not true:(这是不正确的:(
use findall使用 findall
findall(X, (member(X,[a(1),a(2),a(3),b(1)]),\+(X=a(_))) ,V).
I know you said no swi-prolog.我知道你说没有 swi-prolog。 However it's an easy task (compared to the main one), to implement a recursion that behaves the same as the exclude/3
used, the rest should be ISO prolog or present in amzi too.然而,实现与使用的exclude/3
行为相同的递归是一项简单的任务(与主要任务相比),rest 应该是 ISO prolog 或也存在于 amzi 中。 It useslambda.pl , a library that allows easier higher order programming:它使用lambda.pl ,一个允许更简单的高阶编程的库:
:- [lambda].
filter(Term, List, Result) :-
Term =.. [Pred|Args],
length(Args, Arity),
exclude(\X^(X =.. [Pred2|Args2],
length(Args2, Arity2),
Pred == Pred2,
Arity == Arity2), List, Result).
This solution has the advantage of staying away from the unpure findall/3
.该解决方案的优点是远离不纯的findall/3
。
Hope this helps.希望这可以帮助。
Little fix, and it should work:小修复,它应该工作:
% remove_same_indicator(+Callable,+List,-List)
remove_same_indicator(_, [], []).
remove_same_indicator(X, [Y|L], R) :-
functor(X, F, N),
functor(Y, F, N),
!,
remove_same_indicator(X, L, R).
remove_same_indicator(X, [Y|L], [Y|R]) :-
remove_same_indicator(X, L, R).
Let's give it a try:试一试吧:
?- remove_same_indicator(a(_), [a(1),a(2),a(3),b(1)], R).
R = [b(1)]
Advantage over findall solution, one does not loose variables.优于 findall 解决方案,一个不会丢失变量。 For example one can do:例如可以这样做:
?- remove_same_indicator(a(_), [a(A),a(B),a(C),b(A)], R).
R = [b(A)]
But with the findall solution we get:但是使用 findall 解决方案我们得到:
?- L=[a(A),a(B),a(C),b(A)], findall(X, (member(X,L),\+ (X = a(_))), R).
L = [a(A), a(B), a(C), b(A)],
R = [b(_I)]
The argument of b is not anymore bound to A, since findall creates copies and thus new variables. b 的参数不再绑定到 A,因为 findall 创建副本并因此创建新变量。
Bye再见
functor/3 is ISO and also in Amzi! functor/3 是 ISO,也在 Amzi 中!
http://www.amzi.com/manuals/amzi/pro/ref_manipulating_terms.htm#functorTermFunctorN http://www.amzi.com/manuals/amzi/pro/ref_manipulating_terms.htm#functorTermFunctorN
remove_all(_, [], []).
remove_all(X, [Y|R], L):- \+ X \= Y, remove_all(X, R, L).
remove_all(X, [Y|R], [Y|R2]):- X \= Y, remove_all(X, R2, L).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.