简体   繁体   English

Prolog:将递归谓词放入Variable

[英]Prolog: put recursive predicates into Variable

I'm beginner in prolog and I need to resolve the following exercise: 我是序言的新手,我需要解决以下问题:

Write a 3-predicate prereqchain(P,Q,L) that, given two courses P and Q, returns in L a representation of all the steps on a prerequisite path from P to Q. For example prereqchain(comp085,itec450,L) should give the answer 编写一个3谓词prereqchain(P,Q,L),给定两个过程P和Q,它在L中返回从P到Q的前提路径上所有步骤的表示。例如prereqchain(comp085,itec450,L)应该给出答案

L=prerequisite(comp085, comp101, 
prerequisite(comp101, comp281, 
prerequisite(comp281, itec450))).

Basically, the knowledge data base stand for the prerequisite relationship between the degree's courses. 基本上,知识数据库代表学位课程之间的前提关系。 My main problem is, How can I capture the recursive calls trace and put it into variable ? 我的主要问题是,如何捕获递归调用跟踪并将其放入变量? On the other hand, is not really all the trace, because I just need the calls where the variables was replaced with the values. 另一方面,并​​不是所有的跟踪,因为我只需要用变量替换值的调用即可。

Thanks a lot! 非常感谢!

What's your base case? 你的基本情况是什么? It's going to look like this: 它看起来像这样:

prereqchain(Start, End, prerequisite(Start, End)) :-
    prerequisite(Start, End).

This gives you the following situation: 这给您以下情况:

?- prereqchain(comp281, itec450, L).
L = prerequisite(comp281, itec450).

So this is the first thing you need, now what happens when you ask for prereqchain(comp101, itec450) ? 所以这是您需要的第一件事,现在当您要求prereqchain(comp101, itec450)时会发生什么? You need an inductive case that follows the rest of the chain: 您需要遵循其余部分的归纳案例:

prereqchain(Start, End, prerequisite(Start, Middle, Tail)) :-
    prerequisite(Start, Middle),
    prereqchain(Middle, End, Tail).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM