3

Suppose I have the following RDF data:

@prefix : <urn:ex:>

:m  :A  "a"
:m  :A  "b"
:m  :A  "c"
:m  :B  "a"
:m  :B  "b"

What SPARQL query could I use to check whether the RDF model satisfies the following logical formula?

∀x A(X) → B(x)
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
hala
  • 29
  • 5
  • Also see: http://stackoverflow.com/questions/25256452/is-it-possible-to-express-a-recursive-definition-in-sparql . – Joshua Taylor Jun 15 '16 at 12:24
  • 1
    There's a specification that describes exactly how to do this http://docs.stardog.com/icv/icv-specification.html – Michael Jun 16 '16 at 13:20

1 Answers1

5

SPARQL doesn't have conditionals or universal quantification, but does have existentials (does anything match this?), (implicit) conjunction and negation (in the 'absence' sense).

So rewrite the question:

∀x A(x) → B(x) ⇒
∀x ¬ ( A(x) ∧ ¬ B(x) ) ⇒
¬ ∃x A(x) ∧ ¬ B(x)

and that's something SPARQL can do, pretty much:

# Is there anything of type A but not B?
ASK {
  { ?x a :A } MINUS { ?x a :B }
}

This query returns true if there are any violations of the constraint.

user205512
  • 8,798
  • 29
  • 28
  • 1
    This is a very nice use of [**minus**](https://www.w3.org/TR/sparql11-query/#neg-minus). I tend to use **not exists** by default (e.g., `?x a :A . filter not exists { ?x a :B }`, because **minus** can be a bit surprising at times (they don't always produce the same results), but this is a good example of correct use of **minus**. – Joshua Taylor Jun 15 '16 at 12:33
  • 1
    One more note on "If that returns false the test has passed." That's absolutely correct, but it might be easier to think of in terms of the *positive* form of the statement: "The query returns *true* if there are any violations of the constraint." – Joshua Taylor Jun 15 '16 at 12:34
  • 1
    Text stolen :-) Yes, minus feels better here, but like you I incline to filter not exists. – user205512 Jun 16 '16 at 15:58