 //    }
 }
 
+public enum Aggregation {
+    case countAll
+    case count(Expression)
+    case sum(Expression)
+}
+
 public indirect enum Algebra {
     case quad(QuadPattern)
     case triple(TriplePattern)

            let parser = NTriplesPatternParser(reader: "")
            guard let pattern = parser.parseTriplePattern(line: rest) else { return nil }
            return .triple(pattern)
        } else if op == "limit" {
            guard let count = Int(rest) else { return nil }
            guard let child = stack.popLast() else { return nil }

                return false
            }
            return AnyIterator(s.makeIterator())
        case .aggregate(let child, let groups, let aggs):
            let i = try self.evaluate(algebra: child, activeGraph: activeGraph)
            var groupBuckets = [String:[Result]]()
            var groupBindings = [String:[String:Term]]()
            for result in i {
                let group = groups.map { (expr) -> Term? in return try? expr.evaluate(result: result) }
                let groupKey = "\(group)"
                if groupBuckets[groupKey] == nil {
                    groupBuckets[groupKey] = [result]
                    var bindings = [String:Term]()
                    for (g, term) in zip(groups, group) {
                        if case .node(.variable(let name)) = g {
                            if let term = term {
                                bindings[name] = term
                            }
                        }
                    }
                    groupBindings[groupKey] = bindings
                } else {
                    groupBuckets[groupKey]?.append(result)
                }
            }
            var a = groupBuckets.makeIterator()
            return AnyIterator {
                guard let pair = a.next() else { return nil }
                let (groupKey, results) = pair
                guard var bindings = groupBindings[groupKey] else { fatalError("Unexpected missing aggregation group template") }
                for (agg, name) in aggs {
                    switch agg {
                    case .countAll:
                        let count = results.count
                        bindings[name] = Term(value: "\(count)", type: .datatype("http://www.w3.org/2001/XMLSchema#integer"))
                    default:
                        fatalError("Unimplemented aggregate: \(agg)")
                    }
                }
                return Result(bindings: bindings)
            }
        case .bgp(_):
            fatalError("Unimplemented: \(algebra)")
        case .leftOuterJoin(_, _, _):
