Breadth first search in prolog gives me an error

断了今生、忘了曾经 提交于 2020-01-05 05:45:11

问题


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 ?


回答1:


For this solution I used SWI-Prolog

What's going on here?

uncaught exception: error(existence_error(procedure,breadthlirst/2),solve/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.

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).

Executing the query

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

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 ?

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

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

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.




回答2:


Sorry but no street-cred so no commment for MDG :-(

If you want breadth first maybe best to use queue?? I don't know. I can show code for breadth first with queue but this is not your question and there is so many such questions just search no problem.



来源:https://stackoverflow.com/questions/53236609/breadth-first-search-in-prolog-gives-me-an-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!