Prolog中的打印路径 [英] Printing path in Prolog

查看:85
本文介绍了Prolog中的打印路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在有向图中打印节点的路径.此代码适用于边缘,但不适用于整个路径.当涉及到路径时,它返回 false.这是我的代码,但它仅在一个边缘上运行,而不是在整个路径上运行.请帮帮我.

I want to print the path of nodes in a directed graph. This code works properly for an edge but didn't work for the whole path. It returns false when it comes to path. Here is my code but it is only running for just an edge and not for the whole path. Kindly help me out.

这是我的代码:

path(Node1, Node2, X) :-
  edge(Node1, Node2),
  append([Node1], [Node2], X).
path(Node1, Node2, X, N) :-
  edge(Node1, SomeNode),
  append([Node1], [SomeNode], X),
  path(SomeNode, Node2, X, N),
  append([], [Node2], X).

X 是一个列表.

推荐答案

虽然@WouterBeek 已经指出了您的问题,但 Wouter 的声明

While @WouterBeek already pinpointed your problems, Wouter's statement

如果不运行这段代码,您已经可以观察到第二个子句将始终失败,因为长度为 2 的列表无法与长度为 1 的列表统一

Without running this code you can already observe that the second clause will always fail, since a list of length 2 cannot be unified with a list of length 1

值得详细说明.对于有经验的 Prolog 程序员来说,很容易发现这些问题.但是初学者能做什么呢?他们可以应用以下技术:泛化你的程序,如果泛化后的程序仍然过于专业化,那么剩下的部分肯定有错误.

merits some elaboration. For an experienced Prolog programmer it is easy to spot such problems. But what can beginners do? They can apply the following technique: Generalize your program and if the generalized program is still too specialized, there must be an error in the remaining part.

有几种方法可以概括一个纯 Prolog 程序:要么删除目标,要么删除头部或目标的参数中的子项.要删除目标,我将在目标前添加一个 *,使用:

There are several ways to generalize a pure Prolog program: Either remove goals, or remove subterms in arguments of the head or a goal. To remove goals, I will add a * in front of a goal, using:

:- op(950,fy, *).

*_.

path(Node1, Node2, X) :-
  * edge(Node1, Node2),
  append([Node1], [Node2], X).
path(Node1, Node2, X) :-
  * edge(Node1, SomeNode),
  append([Node1], [SomeNode], X),
  * path(SomeNode, Node2, X),
  append([], [Node2], X).

现在我们可以询问这个新谓词的最一般查询:

Now we can ask the most general query of this new predicate:

| ?- path(N1, N2, P).
P = [N1,N2] ? ;
no

因此:虽然这个定义现在是一个(过度)概括,但它仍然只承认长度为2的路径.这个问题完全独立于edge/3的定义,只有剩下的部分负责.所以看看剩下的部分来解决问题!

Therefore: Although this definition is now an (over-) generalization, it still admits only paths of length 2. The problem is completely independent of the definition of edge/3, only the remaining part is responsible. So look at the remaining part to fix the problem!

这篇关于Prolog中的打印路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆