Search code examples
answer-set-programmingclingo

Aggregates in clingo


I have generated :

curr(p5,2) curr(p5,1) curr(p5,6)

How can I sum up the lase fields 2+1+6?

I saw the following in page 21 of clingo_guild.pdf :

15 :- not M-2 [ enroll(C) : hours(C,H) = H ] M, max_hours(M).

and come up :

#sum [pick(P) : curr(P,I) = I].

but I get:

ERROR: unstratified predicate in:
bus3.lp:73:2: #sum[pick(P)=I:curr(P,I)].
bus3.lp:73:17: curr/2

I am using clingo 3.0.4. Thank you for your help.


Solution

  • I'm assuming you'll want the totals for each "pick", and I assume pick is defined as

    pick(P) :- curr(P, _).
    

    You should tell in the code which pick you mean. In the clingo3 guide case you cite this is not needed.

    In clingo3:

    % clingo3
    curr(p4,2). curr(p4,2). curr(p4,6).
    curr(p5,2). curr(p5,1). curr(p5,6).
    
    pick(P) :- curr(P, _).
    % for each pick P, sum all I from matching curr(P, I)
    totals(P, S) :- S = #sum[ curr(P,I) = I ], pick(P).
    
    #hide.
    #show totals/2.
    

    And in clingo4, which uses a more consistent way of expressing these:

    % clingo4
    % ...
    totals(P, S) :- S = #sum{ I : curr(P,I)}, pick(P).
    #show totals/2.