用prolog实现DFS

时间:2017-04-14 22:59:59

标签: prolog

我正在尝试使用Prolog

编写DFS(深度优先搜索)代码
search(Istate,Goal):-
    findPath([(Istate,null)], [], Goal).

findPath([], _, _):- %empty open list
   !, write("No solution found"),nl.
findPath([(Goal,Parent)|_], Closed, Goal):- %Goal has been reached
   printSolution((Goal,Parent), Closed).
findPath([State|RestOfOpen], Closed, Goal):-
    getChildren(State, RestOfOpen, Closed, Children),
    concatenate(Children, RestOfOpen, NewOpen),
    findPath(NewOpen, [State|Closed], Goal).

getChildren((State, _), Open, Closed, Children):-
    bagof((X,State), move(State,X), Open, Closed, Children).

concatenate([],L,L):- !.
concatenate(L,[],L):- !.
concatenate([H|T], L, [H|R]):-
    concatenate(T, L, R).

printSolution((Istate,null),_):-
    !, write(Istate), nl.
printSolution((State, Parent), Closed):-
    SearchInClosed(Parent, Closed, (Parent, GrandParent), NewClosed),
    printSolution((Parent, GrandParent), NewClosed),
    write(State), nl.

SearchInClosed(State, [(State, Parent)|RestOfClosed], (State, Parent), RestOfClosed):- !.
SearchInClosed(State, [H|RestOfClosed], R, [H|NewClosed]):-
    SearchInClosed(State, RestOfClosed, R, NewClosed).

move(State,NewState):- .%to be implemented

但是我收到以下错误"语法错误:运算符预期" 我真的不知道如何解决问题

1 个答案:

答案 0 :(得分:1)

我不知道您的代码是否正确,但语法错误与SearchInClosed以及您的上一条规则有关。 SearchInClosed应以小写字母开头,例如searchInClosed。以大写字母开头的所有内容都是变量。

下一个问题是你的最后一条规则。你可以拿出:-来编译它; :-需要一些代码才能遵循它。这就像一个含义,并且为了暗示有意义,你需要在另一端有东西。

下面是一个将编译的版本。它仍然包含一些警告,但我怀疑它们是代码不完整的结果。重申一下,我没有检查任何正确性。

search(Istate,Goal):-
    findPath([(Istate,null)], [], Goal).

findPath([], _, _):- %empty open list
   !, write("No solution found"),nl.
findPath([(Goal,Parent)|_], Closed, Goal):- %Goal has been reached
   printSolution((Goal,Parent), Closed).
findPath([State|RestOfOpen], Closed, Goal):-
    getChildren(State, RestOfOpen, Closed, Children),
    concatenate(Children, RestOfOpen, NewOpen),
    findPath(NewOpen, [State|Closed], Goal).

getChildren((State, _), Open, Closed, Children):-
    bagof((X,State), move(State,X), Open, Closed, Children).

concatenate([],L,L):- !.
concatenate(L,[],L):- !.
concatenate([H|T], L, [H|R]):-
    concatenate(T, L, R).

printSolution((Istate,null),_):-
    !, write(Istate), nl.
printSolution((State, Parent), Closed):-
    searchInClosed(Parent, Closed, (Parent, GrandParent), NewClosed),
    printSolution((Parent, GrandParent), NewClosed),
    write(State), nl.

searchInClosed(State, [(State, Parent)|RestOfClosed], (State, Parent), RestOfClosed):- !.
searchInClosed(State, [H|RestOfClosed], R, [H|NewClosed]):-
    searchInClosed(State, RestOfClosed, R, NewClosed).

move(State,NewState).%to be implemented