0

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.

Hacker688
  • 93
  • 8
  • 4
    What have you tried? Have you tried looking at the built-in predicates for finding all solutions to a goal? –  Nov 01 '13 at 09:04
  • Ya,I had Tried to first put all modules in a list and then use dif to find different modules,But it does not provide what i required.But now it has been done by use of aggregate.Please help me in finding classmates of branch now. – Hacker688 Nov 03 '13 at 07:36
  • please make a new post with your new question; do not edit the new question in on top of the old one. – Will Ness Nov 03 '13 at 08:09

3 Answers3

1

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.

User
  • 14,131
  • 2
  • 40
  • 59
1
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.

Shon
  • 3,989
  • 1
  • 22
  • 35
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...

CapelliC
  • 59,646
  • 5
  • 47
  • 90