dusa icon indicating copy to clipboard operation
dusa copied to clipboard

Implement demand/magic sets transformation

Open robsimmons opened this issue 1 year ago • 0 comments

I need to better understand how this relates to the "demand" or "magic sets" transformation, but I really think the right move for Dusa is to declare certain predicates to be demand-driven, and then automatically do the magic-sets transformation on them.

In Dusa, it seems reasonable to connect this with the functional predicate transformation: for a predicate d X Y is Z, the only mode you get is d + + is -. That is, the stuff to the left of the “is” is input, the stuff to the right of the “is” is output. It is not particularly orthogonal language design to tie functional predicates to a demand transformation like this, but, well, my hunch is that this will be a lot simpler, and my experience from Advent of Code was that this was the only version that it was painful to do without, and the only one that I wanted.

As a example that's simple but silly because we already have integer addition, we might want to implement unary addition in Dusa:

add z N is N.
add (s N) M is (s P) :- add N M is P.

b P :- a N, a M, add N M is P, c P.

This doesn't work for two reasons:

  1. The first rule isn't range restricted.
  2. The second rule, if it can fire at all, will fire in an unrestricted manner.

The demand/magic sets transformation introduces a new predicate, needAdd. It uses the invariant that we will only introduce a fact of the form add t1 t2 is X if the database already includes a fact of the form needAdd t1 t2. Uses of the demanded add relation in premises require us to add new rules that derive needAdd:

add z N is N :-
   needAdd z N.

needAdd N M :-
   needAdd (s N) M.
add (s N) M is (s P) :-
   add N M is P.

needAdd N M :-
   a N, a M.
b P :-
   a N, a M, add N M is P, c P.

This transformation has the same vibe as the one that translates ASP to Dusa - a negated premise represents a "demand that this attribute potentially be ff"

Note on the literature: I thought "magic sets" and "demand transformation" were the same thing, but according to the "Datalog: concepts, history, and outlook" paper they are different. Possibly they're the same when restricted to operating with functional predicates in the way I'm proposing.

robsimmons avatar Jun 06 '24 11:06 robsimmons