开发者

In Prolog, how can I check for N of elements in list A in list B?

I have these two lists =

fruits([banana, apple, mangoes, pears]).
foodILike([hamburgers, banana, shakes, fri开发者_运维知识库es]).

I want to write a prolog predicate that will return true as soon as it sees 1 items in the foodsILike list in the fruits list. How can I go about doing so?


First, for the plain answer:

fruitsILike(F) :-
  fruits(Fs)
  member(F, Fs),
  foodILike(Ls),
  member(F, Ls).

You could avoid the membership check by flattening the fruits and foods lists:

fruit(banana).
fruit(apple).
...
foodILike(hamburger).
foodILike(banana).
...
fruitsILike(F) :-
  fruit(F),
  foodILike(F).

That said, you seem to try and solve problems in Prolog using imperative idioms, and that won't work. First, predicates do not return anything. When calling a predicate, Prolog unifies its arguments with valid values according to the facts and rules in the program. Therefore, the "returned value" are the assignments to unbound variables. Second, Prolog does not do something "as soon as". It iterates over all possible solutions. You get the first solution, then the second solution, and so on.


member can 1) individually generate all the members of a given list and/or 2) give a yes/no answer as to whether a particular element is in a particular list. I believe you want to use the first form on fruits to generate each of the elements of fruit, and the second form on foodILike to see if any of those is present.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜