Prolog - recursing down family tree

后端 未结 3 1191
孤城傲影
孤城傲影 2021-02-10 20:19

I am trying to write a Prolog program that will print out the male successors of British Royalty in order. My attempt so far:

son(elizabeth, charles).
son(charle         


        
3条回答
  •  清酒与你
    2021-02-10 21:11

    As rati noted above, Prolog queries are resolved by choosing a rule, recursively evaluating it using depth-first search, then choosing the next rule and repeating the process. However, the particular rules you're starting with actually result in a breadth-first search of the family tree, which, as you noted, does not give output that matches the actual line of succession. Instead, you want to do a depth-first traversal of the royal family tree. This version gives the result you're looking for:

    successor(X, Y) :- son(X, Z), (Y = Z; successor(Z, Y)).
    

    Using this rule, Prolog resolves the query successor(X, Y) roughly as follows:

    • For each Z who is a son of X:
      • Bind Y to Z, giving Z as a solution.
      • The ; operator functions as a logical OR, so now Y is unbound and successor/2 is called recursively to get the successors who are sons of Z.

    And yes, please do try to get a copy of the Art of Prolog. It's not the easiest programming book to read, but I found it extremely helpful in my (ongoing) attempt to understand logic programming. There seem to have been some cheap hardcover copies of the 1994 edition floating around eBay lately.

提交回复
热议问题