[comp.lang.prolog] Counting things.

collinge@uvicctr.UUCP (Doug Collinge) (07/02/87)

OK, I looked in Clocksin and Mellish and couldn't find it.  Now I ask you
at the risk of looking foolish...

Say you have a bunch of relations in the database, r(X).  How do you count
up the number of them?  I have been using "setof(X,r(X),LX)" and then 
measuring the length of LX with something else.  This seems crude and brutal
to me - how can I do it directly?

Of course, it is really more complicated than this but this is the kernal of
the problem.

In a related development, can "setof" be  implemented in Prolog? How?
-- 
		Doug Collinge
		School of Music, University of Victoria,
		PO Box 1700, Victoria, B.C.,
		Canada,  V8W 2Y2  
		collinge@uvunix.BITNET
		decvax!uw-beaver!uvicctr!collinge
		ubc-vision!uvicctr!collinge

tim@linc.cis.upenn.edu (Tim Finin) (07/03/87)

Counting the number of clauses in the DB unifying with a given term
using SETOF/BAGOF is the "proper" way to do it.  The other way this
sort of thing is typically done it to use ASSERT/RETRACT to keep a
counter in the DB and use a failure driven loop to find all the 
matches, as in:

	countClauses(X,_) :-
		assert(count(0)),
		clause(X,true),
		retract(count(N)),
		N2 is N+1,
		assert(count(N2)),
		fail.

	countClauses(_,N) :- retract(counter(N)).

There is, as I recall, a definition of a predicate FINDALL in C&M
which is similar to BAGOF and SETOF.

Tim