在序言中进行广度优先搜索给我一个错误 [英] Breadth first search in prolog gives me an error

查看:123
本文介绍了在序言中进行广度优先搜索给我一个错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在序言中广度优先搜索策略的代码:

This is my code for breadth first search strategy in prolog :

s(a, b).
s(a, c).
s(b, g).
s(b, f).
s(c, r).
s(c, e).
goal(g).

solve( Start, Solution) :-
    breadthlirst( [ [Start] ], Solution).

breadthfirst( [ [Node | Path] |_], [Node | Path] ) :-
    goal( Node).

breadthfirst( [ [N | Path] | Paths], Solution) :-
    bagof([M,N|Path],
    ( s( N, M), \+ member( M, [N | Path] ) ), NewPaths),
    conc( Paths, NewPaths, Pathsl), !,
    breadthfirs( Pathsl, Solution);
    breadthfirst( Paths, Solution). 

但是当我运行这段代码时,它发出了一个异常:

But when I run this code it issue an exception as so :

?- solve(a, S).
uncaught exception: error(existence_error(procedure,breadthlirst/2),solve/2)

这是怎么回事?另外,有没有比这更容易的广度优先搜索版本?

What's going on here? also, is there any easier version of breadth first search than this one ?

推荐答案

对于此解决方案,我使用了SWI-Prolog

For this solution I used SWI-Prolog


这是怎么回事?

What's going on here?



uncaught exception: error(existence_error(procedure,breadthlirst/2),solve/2)

编译器/解释器向您展示了解决您的查询时,它以谓词 solve / 2 开头,然后尝试查找它无法找到的 breadthlirst / 2

The compiler/interpreter is showing you that in trying to solve your query it started with predicate solve/2 and then tried to find breadthlirst/2 which it could not.

修正拼写错误并将 conc / 3 更改为 append / 3 导致

Fixing the typos and changing conc/3 to append/3 results in

s(a, b).
s(a, c).
s(b, g).
s(b, f).
s(c, r).
s(c, e).
goal(g).

solve( Start, Solution) :-
    breadthfirst( [ [Start] ], Solution).

breadthfirst( [ [Node | Path] |_], [Node | Path] ) :-
    goal( Node).

breadthfirst( [ [N | Path] | Paths], Solution) :-
    bagof([M,N|Path],
    ( s( N, M), \+ member( M, [N | Path] ) ), NewPaths),
    %conc( Paths, NewPaths, Pathsl), !,
    append(Paths, NewPaths, Pathsl), !,
    breadthfirst( Pathsl, Solution);
    breadthfirst( Paths, Solution).

执行查询

?- solve(a,S).
S = [g, b, a] ;

通常情况下,我希望达到目标,在这种情况下, g 作为求解的参数,而不是作为事实 goal(g)进行硬编码。

Normally I would expect the goal, in this case g to be a parameter of solve and not hard coded as a fact goal(g).


广度优先搜索是否比这个更容易?

Is there any easier version of breadth first search than this one ?

在Prolog中进行呼吸优先搜索时除了琐碎的情况外,我更喜欢使用元解释器

When working with breath first search in Prolog beyond trivial cases I prefer to use meta-interpreters.

此处是Prolog中BFS的另一个版本,如果您在Prolog上获得任何血统书,它应涵盖BFS。

Here is another version of BFS in Prolog and if you get any descent book on Prolog it should cover BFS.

序言的力量将为您提供帮助更好地了解Prolog。请注意,这是更多高级内容,除非您了解基本知识,否则不可以开始使用。

The Power of Prolog will help you with understanding Prolog better. Be warned that this is more of the advanced stuff and not something to start playing with until you understand the basics.

这篇关于在序言中进行广度优先搜索给我一个错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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