Search code examples
recursionprologprolog-cut

advice needed with prolog cut?


in this task i have a Prolog database filled with e.g. edge(1,0) edge(2,0) edge(1,3)

an edge signifies that two points are joined.

I am asked to write a function called reach(i,j,k) where i is the start point j is the end point and k is the number of steps you may use. K is needed to stop the recursion looping e.g.

Suppose the only edge I’ve got goes from 1 to3,and I’m trying to get to 6. Then I can’t get from 1to6 in one go. so I’ll look for somewhere I can get to, and see if I can get from there to 6. The first place I can get to in one go is 3, so I’ll try to get from there to 6.

i have done this as so:

    %% Can you get there in one step (need two rules because all links are
%% from smaller to greater, but we may need to get from greater to smaller.

reach1(I, J,_K) :-
    edge(I, J).
reach1(I, J,_K) :-
    edge(J, I).
%% Chhose somewhere you can get to in one step: can you get from there
%% to your target?
reach1(I,J,K) :-
    K>1,
    edge(I, B),
    K1 is K-1,
    reach1(B,J,K1).

reach1(I,J,K) :-
    K>1,
    edge(B, I),
    K1 is K-1, 
    reach1(B,J,K1).

this works, however i am stuck with the second part in which we are asked not to use k but to use a "cut" to do this.

does anyone know how to do this or can give me some pointers?


Solution

  • The cut ensures that once a goal has been resolved in one way, it doesn't look for another way.

    example:

    reach(I, J,_K) :-
        edge(I, J).
    

    no cut - if for some reason Prolog backtracks, it will try to reach from I to J another way. You might feel there's no point reaching this node another way if the simple edge works, and in that case you can do:

    reach(I, J,_K) :-
        edge(I, J),
        !.
    

    which "cuts" any alternative to this goal, but the one Prolog has found.