+ simplify conjunctions
authorEric Prud'hommeaux <eric@w3.org>
Wed, 10 Feb 2010 18:28:25 -0500
changeset 162 800b4d9d114d
parent 161 ce95b5ab3d6c
child 163 90cd6100e605
+ simplify conjunctions
src/main/scala/SPARQL.scala
src/main/scala/SparqlToSparql.scala
src/test/scala/SparqlToSparqlTest.scala
--- a/src/main/scala/SPARQL.scala	Wed Feb 10 18:27:56 2010 -0500
+++ b/src/main/scala/SPARQL.scala	Wed Feb 10 18:28:25 2010 -0500
@@ -71,6 +71,42 @@
       case x => error("no code to handle " + x)
     }
   }
+
+  def simplify ():GraphPattern = {
+    this match {
+      case TableFilter(gp2:GraphPattern, expr:Expression) =>
+	TableFilter(gp2.simplify, expr)
+
+      case tb:TriplesBlock => tb
+
+      case TableConjunction(list) => {
+	/* Eliminate series of TriplesBlocks. */
+	val (conjuncts, triples) = list.foldLeft((List[GraphPattern](), List[TriplePattern]()))((pair, gp2) => {
+	  val (conj, trip) = pair
+	  val gp3 = gp2.simplify
+	  gp3 match {
+	    case TriplesBlock(triplepatterns) =>
+	      (conj, trip ++ triplepatterns)
+	    case x => {
+	      (conj ++ List(TriplesBlock(trip)), List[TriplePattern]())
+	    }
+	  }
+	})
+	val conj2 =
+	  if (triples.size > 0) conjuncts ++ List(TriplesBlock(triples))
+	  else conjuncts
+	if (conj2.size > 1) TableConjunction(conj2)
+	else if (conj2.size == 1) conj2(0)
+	else TriplesBlock(List[TriplePattern]())
+      }
+
+      case OptionalGraphPattern(gp2) =>
+	/* Examine each triple, updating the compilation state. */
+	OptionalGraphPattern(gp2.simplify)
+
+      case x => error("no code to handle " + x)
+    }
+  }
 }
 
 case class TriplesBlock(triplepatterns:List[TriplePattern]) extends GraphPattern {
--- a/src/main/scala/SparqlToSparql.scala	Wed Feb 10 18:27:56 2010 -0500
+++ b/src/main/scala/SparqlToSparql.scala	Wed Feb 10 18:28:25 2010 -0500
@@ -80,7 +80,7 @@
       if (conjuncts.size == 0)
 	sparql.TriplesBlock(List[sparql.TriplePattern]())
       else if (conjuncts.size > 1)
-	sparql.TableConjunction(conjuncts)
+	sparql.TableConjunction(conjuncts).simplify
       else
 	conjuncts(0)
     }
--- a/src/test/scala/SparqlToSparqlTest.scala	Wed Feb 10 18:27:56 2010 -0500
+++ b/src/test/scala/SparqlToSparqlTest.scala	Wed Feb 10 18:28:25 2010 -0500
@@ -164,12 +164,12 @@
 PREFIX task : <http://hr.example/DB/Task#>
 PREFIX xsd : <http://www.w3.org/2001/XMLSchema#>
 SELECT ?lname
-     {{?who     empP:lastName   ?lname .
+     { ?who     empP:lastName   ?lname .
        ?_0_pair task:drone      ?who .
-       ?_0_pair task:manager    ?whom }
-      {?_1_pair task:drone      ?whom .
+       ?_0_pair task:manager    ?whom .
+       ?_1_pair task:drone      ?whom .
        ?_1_pair task:manager    ?whom2 .
-       ?whom2   empP:lastName   "Smith"^^xsd:string }
+       ?whom2   empP:lastName   "Smith"^^xsd:string
      }
 """).get
     assert(transformed === expected)