3

Could you please help me to convert the below of my code into the one using the failure-driven loop (without using recursion)?

I coded a simple failure-driven loop that prints the elements in a list without recursive code.

print_path(List) :- member(X, List), write(X), fail.
print_path(_).

Now I wonder if BFS also can be implemented without recursive code and coded in a similar way but it just ends as false. I appreciate if you could let me know what I'm missing or even if it's possible.

BFS with recursive code successfully works.

% terminate when reached a goal.
dfs([Goal|Path]).

% find a goal state recursively keeping track of a non-visited path.
dfs([State|Path]) :-
    move(State, Next),
    not(member(Next, Path)),
    dfs([Next, State|Path]).

BFS with failure-driven loop that I have trouble with.

dfs(Start):-
    path(Start),
    dfs1([Start]).

% terminate when reached a goal.
dfs1([Goal|Path]).

% find a goal state recursively keeping track of a non-visited path.
dfs1([State|Path]) :-
    move(State, Next),
    not(member(Next, Path)),
    assert(path([Next, State|Path])),fail.

[Update] : Please note that I can't add comment because I don't have 50 reputations as a new user. What I want is the possible solution paths for the famous farmer problem, so the start state is [e,e,e,e] and the goal state is [w,w,w,w] to be moved forward with move/2. I don't know about iterative deepening as I'm still beginner level so the explanation or sample code in detail is much appreciated:) Thank you.

false
  • 10,264
  • 13
  • 101
  • 209
Dora2928
  • 31
  • 1
  • 1
    Consider iterative deepening! like `length(Path, N), path(move, Path, Start,X)` using [`path/4`](https://stackoverflow.com/q/30328433/772868). – false Feb 18 '19 at 13:51
  • 1
    What is not clear to me: What do you actually want? If `move/2` has only finitely many solutions, then `path(move, Path, Start,X)` works as is, only if it has infinitely many solutions you will need `length(Path, N)` in front – false Feb 18 '19 at 14:04
  • You keep on writing "BFS" (*Breadth* first search) in the question. You mean "DFS" (Depth first search), right? You could maybe edit the question of clear up the confusion somehow? – User9213 Feb 21 '19 at 07:50

0 Answers0