1
votes

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.

1
How to ask a good question: stackoverflow.com/help/how-to-ask - user1812457
You don't need element/2. Prolog already has member/2, e.g., member(b, [a,b,c]) is true. And per Boris' comment, read the documentation on how to ask a good question. You need to better describe specifically what you want your code to do and what it actually does. Showing examples helps. - lurker
If isAllergic(john, [fish, milk]) is true, how is it that john can drink milk, per your code comment? This code is very confusing. It's quite unclear what your facts and predicates really mean. - lurker
sorry, my mistake! Of course he cant drink milk, sorry :/ - Vojtech Cerveny

1 Answers

1
votes

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.