首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >追踪prolog递归深度的方法?

追踪prolog递归深度的方法?
EN

Stack Overflow用户
提问于 2016-10-15 03:34:01
回答 1查看 240关注 0票数 1

在prolog中,我的数据库设置如下

代码语言:javascript
复制
male("John").
male("Bob").
male("Billy").
male("Gary").

Parent("Bob","John").
Parent("Billy","Bob").
Parent("Gary", "Billy").


ancestor(Ancestor, Descendant) :-
    parent(Ancestor, Descendant).
ancestor(Ancestor, Descendant) :-
    parent(Ancestor, CommonAncestor),
    ancestor(CommonAncestor, Descendant).

是否有可能跟踪这个祖先函数的递归有多深?例如,如果我们跑

代码语言:javascript
复制
?- ancestor("Billy", "John", X).

是否有可能有X返回2,或在情况下

代码语言:javascript
复制
?- ancestor("Bob", "John", X).

有X返回1吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-15 05:39:29

哟可以写:

代码语言:javascript
复制
ancestor(Ancestor, Descendant,1) :-
    parent(Ancestor, Descendant).
ancestor(Ancestor, Descendant,X) :-
    parent(Ancestor, CommonAncestor),
    ancestor(CommonAncestor, Descendant,X1),
    X is X1+1.

下面是一些例子:

代码语言:javascript
复制
?- ancestor("Billy", "John", X).
X = 2 ;
false.

?- ancestor("Bob", "John", X).
X = 1 ;
false.
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40054664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档