The following is a simple program establishing basic facts in a prolog database.
% main meal
homemade(pizza).
homemade(soup).
% dessert
ripe(apple).
ripe(orange).
% meal is homemade dish and ripe fruit
meal(Main, Fruit) :- homemade(Main), !, ripe(Fruit).
The definition of a meal uses a cut !
for no other reason than to experiment and learn about the cut.
The following general query generates two solutions.
?- meal(M,F).
F = apple,
M = pizza
F = orange,
M = pizza
Question
Prolog's resolution strategy is said to be depth-first. That might suggest we get answers involving both M=pizza
and M=soup
.
Why are we not getting this?
Is the answer that "resolution" of queries to find the first candidate answer is depth first, but solution search is breadth-first (left-to-right along rule bodies)? And that here there is no depth required to resolve the first goal homemade(Main)
.
As you can see I need some clarity on this distinction.
That is depth first; the search tree of your code is:
root meal(Main, Fruit)
/ \ requires
/ \
pizza soup homemade(Main) choice of 2x
/ \ / \ and with the chosen Main
apple orange apple orange ripe(Fruit) combinatorial choice of 4x pairs
Depth first is root, down pizza, down apple, up pizza, down orange, up pizza, up root, down soup, down apple, up soup, down orange.
Breadth first might be depth 0 root; depth 1 down pizza, up root, down soup. Depth 2 root, down pizza, down apple, up pizza, down orange, up pizza, up root, down soup, down apple, up soup, down orange. (Your meal()
depends on visiting down to the leaves of the search tree and the answers would come out the same, I think; depth first is more useful if the tree is unbounded (recursive) and depth first gets stuck forever in an endless left branch. Breadth first forces it to come back up and look elsewhere).
Prolog's resolution strategy is said to be depth-first. That might suggest we get answers involving both M=pizza and M=soup.
Why are we not getting this?
Because you cut them out. Cut says "cut the rest of the tree off, this branch where I am is the only one I want to search in now". homemade(pizza) is the first result of homemade(M)
by either search strategy. Then cut !
commits to that branch of the search tree, so the entire soup side of the tree is not searched so you get homemade(pizza), ripe(apple)
and homemade(pizza), ripe(orange)
as the two results.