0

I am sorry to ask this question, but it has been a lot since I programmed in Prolog. I think I am used to imperative paradigm. :-(

I am trying to obtain itemsets from a Prolog relation:

% transaction(Time, Client, Item)
transaction(1, 2, 10).
transaction(1, 2, 20).
transaction(2, 5, 90).
transaction(3, 2, 30).
transaction(4, 2, 40).
transaction(4, 2, 60).
transaction(4, 2, 70).
transaction(5, 4, 30).
transaction(5, 3, 30).
transaction(5, 3, 50).
transaction(5, 3, 70).
transaction(5, 1, 30).
transaction(6, 1, 90).
transaction(6, 4, 40).
transaction(6, 4, 70).
transaction(7, 4, 90).

% Transformation of transactions to Lists of items per Time per Client.
transaction2(Time, Client, List) :-
    setof(Item, Time^Client^transaction(Time, Client, Item), List).

% Itemsets.
itemsets :-
    transaction(Time, Client, _),
    transaction2(Time, Client, List),
    assert(init(List)).

% Main:
main(Itemsets) :-
    itemsets,
    setof(Basket, init(Basket), Itemsets),
    retractall(init(Basket)).

Then if I consult main(X) I would like to obtain:

X = [[10, 20], [30], [30, 50, 70], [40, 60, 70], [40, 70], [90]]

I just can't figure out a proper way of doing this.

If I can get a pointer or a little help I will appreciate very much.

Bests,

B.

false
  • 10,264
  • 13
  • 101
  • 209

2 Answers2

2

Try

itemsets(L):-
  setof(Items,
   Time^Client^Item^Nil^(
     transaction(Time, Client, Nil),
     setof(Item, transaction(Time, Client, Item), Items)
    ), L).

and just call itemsets(Itemsets).

gusbro
  • 22,357
  • 35
  • 46
  • Hi! Thank you very much! It worked right away. Where can I learn more about setof and Nil? I've been reading the SWI Prolog and XSB manuals in order to understand better setof but I think I would need a deeper explanation with examples. Google has not been of help. Maybe I am not using the right keywords... – B. Solano May 05 '11 at 21:25
  • look for bagof/3 also. There is not much information but I guess that you will learn trying some examples. – gusbro May 05 '11 at 21:38
  • +1 to gusbro. @B. Solano: read the section on `bagof/3` at [*LPN*](http://cs.union.edu/~striegnk/learn-prolog-now/html/node97.html#subsec.l11.bagof), then the next section on `setof/3`. – Fred Foo May 06 '11 at 08:58
0

main(Items) :-
        findsetof([T1,C1],transaction(T1,C1,_),L1),
        findsetof(L2,(
                    append(_,[[T2,C2]|_],L1),
                    findsetof(Item,transaction(T2,C2,Item),L2)),
                Items).

findsetof(A,B,L) :-
        findall(A,B,C),
        setof(A,member(A,C),L).
尾崎隆大
  • 148
  • 1
  • 1