RU beehive logo promo banner for Computing & Info Sciences
CS 380
2025spring
ibarland

Prolog: recursive relations

We will again (in class) use swi-prolog.org's online interpreter. If you're interested in a different explanation/view, here is another prolog tutorial: www.doc.gold.ac.uk/~mas02gw/prolog_tutorial/prologpages/

You can also run /usr/local/bin/xsb from rucs.
In XSB, you can load a file family.pl from the xsb prompt, by typing: [family].

warning: Don't include spaces or hyphens in your filename. xsb interprets hyphens as subtraction, spaces as a list with two objects, and gives a syntax error.

We will use for the following (resulting in ):
  1. Review: facts vs rules
  2. a standard family-tree example, with rules like “father(X,Y) :- male(X), parent(X,Y).”.
  3. Self-exercise: grandfather, w/ a partner.
    (What is the def'n in English, for "Old is a grandparent of Yng"?)
  4. talk/reflect about how this is declarative programming (just saying 'prolog searches for all solutions', without saying more);
  5. write a recursive rule, “ancestor/2”. (note that the “/2” is not part of the name per se; it indicates that ancestor is a binary predicate — so you'll say make queries like ancestor(bart,lisaJr).
  6. have them take a crack at writing with a partner:
    1. nth-father (generalized grandfather; call 'ancestor')
    2. sameLastName (or, “sameYChromosone”): check for male-only lineage
  7. Write cousin.
  8. Digress, in English:
    cousin, 2nd cousin, 3rd cousin;
    nth cousin m times removed.
  9. Write nthCousin (which detects exact nth-cousins, 0 times removed)
  10. Remember facts just rules w/o variables; no intrinsic difference inside prolog.
  11. Helpful tips: trace, with a few further tips here.

logo for creative commons by-attribution license
This page licensed CC-BY 4.0 Ian Barland
Page last generated
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.