Reputation: 696
I have a little problem with define facts and search in array in Prolog. I dont know, how add to rule my array and result of it.
Ok, need some like this:
% John is allergic to fish and milk.
isAllergic(john, [fish, milk]).
% food shark has allergen fish and john cant eat it and drink milk
allergen(shark, fish).
allergen(milk, milk).
%I need list of food, what person (john) can eat.
foodForPerson(F,C):- isAllergic(F, X), allergen(X,C).
And then I call FoodForPerson(john,X), but result is false. I think, that problem is in array. Result should be X=milk, X=shark.
Upvotes: 1
Views: 964
Reputation: 476750
You are missing a member/2
call to get an element out of an array:
foodForPerson(F,C) :-
isAllergic(F, Xs),
members(X,Xs),
allergen(X,C).
Although a better way to represent this is using facts, instead of lists, thus:
isAllergic(john, fish).
isAllergic(john, milk).
In that case your proposed predicate would have worked. And furthermore it's easy to assert
and retract
single facts. Or combine different libariries how each know something about John.
Edit
In case you wish to use a list for allergen
as well, you can make use of member twice:
isAllergic(john, [fish, milk]).
allergen(sharkWitHPotato, [fish, potato]).
foodForPerson(F,X) :-
isAllergic(F, As),
allergen(X,Cs),
member(A,As),
member(A,Cs).
Note that in your comment, you swapped the arguments of allergen
I guess?
But this can result in listing the same tuple john,sharkWitHPotato
multiple times.
Upvotes: 1