Re: Can anyone explain this
Daniel Lyons <[email protected]>
| Newsgroups | gmane.comp.ai.prolog.swi |
|---|---|
| Message-ID | <[email protected]> |
roelof writes: > Hello, > > Im following the Adventure in Prolog tutorial from Amzi. > > then I see this : location(X, kitchen), write(X) ,nl, fail. > > Why not just using : location(X, kitchen) > I can understand why write(X) is mentioned. that's to write the item on > screen. > But why stop with fail ? This is called a failure-driven loop. The idea is to enumerate everything in the kitchen. Supposing you have the basic fact database in part 4, your database contains this: location(apple, kitchen). location(broccoli, kitchen). location(crackers, kitchen). The query will initially unify X with apple. Then it will write 'apple' to the terminal, then a newline, and then it will fail. The failure will cause Prolog to back up to location(X, kitchen) and try to unify something else with X. So it will get and output broccoli, and then it will fail and back up again, and output crackers. After that, there will be no more facts to unify with X, so it will just fail. The very section you're in gives a hugely detailed discussion of how this query will be resolved: http://www.amzi.com/AdventureInProlog/a4comqry.php This behavior is one of the defining characteristics of Prolog. We seem to love foisting failure-driven loops on beginners, but eventually we all get sick of them and turn to recursion and higher-order functions, which have cleaner compositional semantics and don't feel quite so much like an abuse of power. -- Daniel Lyons