Muljayan
Muljayan

Reputation: 3886

How to print out all the facts in prolog

I have a set of rules and a function which prints out all the animals as follows.

animal(dog).
animal(cat).
animal(rat).

printAnimals :-
  animal(X),
  format("~q",[X]).

In the terminal when i type out printAnimals. I only get dog. cat and rat only get printed when i press the ; button. How do i modify this function to print out all the animals without having to press ;.

Upvotes: 0

Views: 456

Answers (1)

David Tonhofer
David Tonhofer

Reputation: 15316

In your approach, backtracking is interactive and occurs at the REPL (the Prolog toplevel) by pressing ;.

You have to collect all the animals either by using one of the meta-predicates

to create a list of animals which can then be printed using maplist/2.

You can also use forall/2 to emit side-effects as animals are collected.

Or you can write a failure-driven loop:

printAllAnimals :-
  animal(X),
  format("~q",[X]),
  fail. % failure causes backtracking to animal(X), which collects the next animal

Upvotes: 3

Related Questions