开发者

Query for facts from list

开发者 https://www.devze.com 2023-02-13 01:33 出处:网络
I am new to prolog and i want to solve this problem. Suppose I have a list say List i.e.[a,b,c] now i have some facts say开发者_运维百科

I am new to prolog and i want to solve this problem. Suppose I have a list say

List i.e. [a,b,c]

now i have some facts say开发者_运维百科

likes(a,banana).

likes(b,orange).

likes(c,apple).

likes(d,grapes).


So if I make a query

?- my_functor(List,X).

X=[banana,orange,apple].


Thanks you.


Consider:

?- List=[a,b,c], findall(X, (member(Y, List), likes(Y, X)), Xs).
List = [a, b, c],
Xs = [banana, orange, apple].

Explanation:

findall/3 is called an 'all-solutions' predicate which seeks to find all possible values unifiable to the first argument (here, that's the variable X) to solutions for the seconds argument (here, that's the conjunction (member(Y, List), likes(Y, X))), and places all values for X into a list, bound to the third argument (here, that's Xs).

Notice that the inner expression generating the values for X is a statement that backtracks to provide different assignments for X:

?- member(Y, [a,b,c]), likes(Y, X).
Y = a,
X = banana ;
Y = b,
X = orange ;
Y = c,
X = apple ;
false.

Tested with SWI-Prolog.

Note that findall/3 also appears in GNU Prolog amongst most other implementations.

0

精彩评论

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