xLCaliburn
xLCaliburn

Reputation: 23

Prolog - How to use the facts in an array of facts?

Beginner to prolog here; just wanted to ask a question to get rid of some of the confusion I am having with an assignment question.

Suppose I had a list of facts (in this case, a list of people and foods they eat and # of items),

label(test,
  [eats(george,apple,3),
   eats(bob,orange,1),
   eats(joe,steak,1)]).

how do I use the facts inside this array? For example, how would I get this to work?

eaten(Person,Food):-
  eats(Person,Food,_).

Upvotes: 0

Views: 480

Answers (2)

CapelliC
CapelliC

Reputation: 60034

I think your question make little sense because of lack of context.

A possible usage for a list of facts it's to push it in DB:

?- maplist(assert, [eats(george,apple,3), eats(bob,orange,1), eats(joe,steak,1)]).
true.

?- eats(Person,Food,_).
Person = george,
Food = apple ;
Person = bob,
Food = orange ;
Person = joe,
Food = steak.

but again, it's all about your remaining rules...

edit Usually the 'information flow' is reversed: we start from DB facts, collects relevant data to a list and process the list. Daniel explained about accessing elements of the list. Consider that after the assertion of facts from the list, your rules will have access to facts. With the rule you listed, after:

?- retractall(eats(_,_,_)),
   maplist(assert, [eats(george,apple,3), eats(bob,orange,1), eats(joe,steak,1)]).

?- eaten(bob,X).
X = orange.

HTH

Upvotes: 1

Daniel Lyons
Daniel Lyons

Reputation: 22803

I think I see what you're asking. The answer is to use member/2 like this:

eaten(Person, Food) :- 
  label(test, Eating),
  member(eats(Person, Food, _), Eating).

Is this the result you want?

?- eaten(P, F).
P = george,
F = apple ;
P = bob,
F = orange ;
P = joe,
F = steak.

As a rule of thumb, it would probably be more "standard" to pass the list along than to store it in a big clump like that. And I would probably say that this is a list of eats/3 structures rather than facts, but this usage kind of blurs the distinction, since what's in the database is a an arity 2 fact called label rather than a group of arity 3 facts called eats. But they are actually in the database, in a roundabout way. Interesting.

This approach, using member to poke through a list, is also commonly used to supply options to a procedure. open/4 uses it, for instance.

Upvotes: 1

Related Questions