Prolog Count The Unique Identifiers In Fact [closed]

陌路散爱 提交于 2019-12-12 02:45:01

问题


We have facts

studies(cse, plc).
studies(cse, da). 
studies(it, se). 
studies(it, plc).  

where studies(x,y) means that branch x studies module y . Now I Want to define Rule To count number of modules in all. like here it will be 3.that are (plc,da,se).PLZ HELP.

What will be the query to find how many subjects studies under CSE.


回答1:


having tagged SWI-Prolog your question, take a look at library(aggregate):

?- aggregate(count, Module, Branch^studies(Branch, Module), N).
N = 3.

library(aggregate) is powerful, learning about it can be really rewarding...




回答2:


I will not tell you the solution but this can help you to find it out by yourself:

If you want to count the modules then you need a list of modules and take its length.

Always remember this sentence:

A list is either an empty list or an element and a list.

Using this you can construct lists of your modules recursively.

Make sure, no element is in the list twice.




回答3:


number_of_modules(N) :-
    findall(M, studies(_,M), Ms),
    sort(Ms, SortedMs),
    length(SortedMs, N).


?- number_of_modules(N).
N = 3.

sort/2 removes duplicate elements.

The arguments of findall/3 are, from left to right, (1) a template for the answer which is to be collected, (2) the goal from which the answer is drawn, (3) the a list of all answers. So you could, for instance, label each module as such by using a different template in (1):

number_of_modules(N, SortedMs) :-
    findall(module(M), studies(_,M), Ms),
    sort(Ms, SortedMs),
    length(SortedMs, N).

?- number_of_modules(N, Ms).
N = 3,
Ms = [module(da), module(plc), module(se)].

Documentation on this and related predicates can be found in section 4.3 of the manual.



来源:https://stackoverflow.com/questions/19722678/prolog-count-the-unique-identifiers-in-fact

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!