Prolog 查找所有路径实现 [英] Prolog find all paths Implementation
问题描述
我的任务是在 Prolog 中实现一个 findall 版本,除了 not 和 cut 之外,不使用任何 Prolog 内置函数 - 所以基本上是纯 Prolog.
I've been tasked to implement a version of findall in Prolog without using any Prolog built-ins except for not and cut - so basically in pure Prolog.
我正在尝试搜索所有直接后代的树并将结果返回到列表中
I'm trying to search a tree for all direct descendants and return the results in a list
parent(a, b).
parent(b, c).
parent(b, d).
parent(e, d).
到目前为止我所拥有的是:
What I have so far is:
find(X, L) :- find2(X, [], L).
find2(X, Acc, L) :- parent(Y, X), find2(Y, [Y|Acc], L).
find2(_, Acc, Acc).
我想在输入时得到什么,例如:
What I want to be getting when I enter for example:
find(a,X).
应该是:
X = [b, c, d]
(顺序不重要)
但是我得到了:
X = [b, c] ;
X = [b, d] ;
X = [b] ;
X = [].
我是 Prolog 的新手,因此不胜感激.
I'm new to Prolog so any help on this would be much appreciated.
谢谢
推荐答案
感谢大家的帮助.我最终通过添加一个谓词来解决它,该谓词根据当前列表检查每个项目,如果它已经存在则失败:
Thanks for you help everyone. I managed to sovle it in the end by adding a predicate which checked each item against the current list, and failed if it was already present:
find(X, Loa) :- find(X, [], Loa), !.
find(X, Acc, Loa) :- dec(Y, X), uList(Y, Acc, AccNew), find(X, AccNew, Loa).
find(_, Acc, Acc).
dec(X,Y) :- parent(X,Y).
dec(X,Y) :- parent(X,Z), dec(Z,Y).
uList(X, [], [X]) :- !.
uList(H, [H|_], _) :- !, fail.
uList(X, [H|T], L) :- uList(X, T, Rtn), L = [H|Rtn].
这篇关于Prolog 查找所有路径实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!