0

Is it possible in Datalog to write a query for facts where there is exactly one value for one of the variables, for each possible value of the other variables?

e.g. find all X such that there is only one X for each Y in expr(X, Y)

Filip Haglund
  • 13,919
  • 13
  • 64
  • 113

1 Answers1

1

In plain Datalog you can express this by first computing the Y's that have more than one X, and then using that to compute the Y's with 1 X.

  problem(y) <- expr(x1, y), expr(x2, y), x1 != x2.
  exactly_one_opt1(y) <- expr(_, y), !problem(y).

Most systems also support aggregations that will probably be a more efficient solution, but aggregation syntax is not standard Datalog. I'm using the LogiQL (LogicBlox Datalog) syntax here:

  count[y] = c <- agg<<c = count()>> expr(_, y).
  exactly_one_opt2(y) <- count[y] = 1.
  • Are you sure the first one is standard Datalog? Is negation a standard feature? – Filip Haglund Oct 26 '16 at 07:47
  • There is no formal standard, but negation is supported by every Datalog variant I'm aware of, so I'd say you can consider it a standard feature. This example here is a very basic usage of negation. The semantics of negation only becomes challenging when negation is used in recursion (most systems implemented something called stratified negation) or when a variable used in negation is not bound positively in the rule (known as unsafe negation). – Martin Bravenboer Oct 27 '16 at 02:24