Prolog recursion and building output from recursive calls

前端 未结 1 1168
攒了一身酷
攒了一身酷 2021-01-07 05:21

I am learning Prolog via http://www.learnprolognow.org and I am having some trouble understanding how to recursively build up a variable with results from another recursive

相关标签:
1条回答
  • 2021-01-07 06:06

    I had a go at this. I made one change to your first solution, just to remove some redundancy. I used the predicate connected/2 to generalize the relationship common to all connections appearing in the by_car/2, by_train/2, and by_plane/2 facts:

    connected(From, To) :- by_car(From, To).
    connected(From, To) :- by_train(From, To).
    connected(From, To) :- by_plane(From, To).
    

    Then I defined travel/2 as a recursive relationship over connected/2:

    travel(From, To) :-
        connected(From, To).
    travel(From, To) :-
        connected(From, Through),
        travel(Through, To).
    

    Turning to travel/3, notice that the final connection in the nested go... terms is a structure go/2, but the rest are go/3s. So we need to populate X with a series of nested go/3 structures that terminate in a go/2. This last is our base condition. Then it is simply a matter of repeating the second clause of travel/2, but including a go/3 in the third argument that will capture the values instantiated to From and Through on each iteration:

    travel(From, To, go(From, To)) :-
        connected(From, To).
    travel(From, To, go(From, Through, Route)) :-
        connected(From, Through),
        travel(Through, To, Route).
    
    0 讨论(0)
提交回复
热议问题