Skip to content

Commit da78613

Browse files
authored
Merge pull request #11 from /issues/10-merge-kb
Issues/10 merge kb
2 parents 0b70c2f + 6879b17 commit da78613

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

Sources/LogicKit/KnowledgeBase.swift

+4-3
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,11 @@ public struct KnowledgeBase: Hashable {
9595

9696
public static func + (lhs: KnowledgeBase, rhs: KnowledgeBase) -> KnowledgeBase {
9797
var result = KnowledgeBase(knowledge: [])
98-
for (name, terms) in lhs.predicates {
99-
result.predicates[name] = terms
98+
for name in lhs.predicates.keys.concatenated(with: rhs.predicates.keys) {
99+
result.predicates[name] = lhs.predicates[name] ?? []
100100
if let right = rhs.predicates[name] {
101-
result.predicates[name]!.append(contentsOf: right)
101+
let set = Set(result.predicates[name]!)
102+
result.predicates[name]?.append(contentsOf: right.filter({ !set.contains($0) }))
102103
}
103104
}
104105
result.literals = lhs.literals.union(rhs.literals)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
@testable import LogicKit
2+
import XCTest
3+
4+
class KnowledgeBaseTests: XCTestCase {
5+
6+
func testMerge() {
7+
let kb1: KnowledgeBase = [
8+
.fact("foo", "bar"),
9+
.rule("foo", .var("x")) {
10+
.fact("foo", .var("x"))
11+
},
12+
.lit(12),
13+
.lit(13),
14+
]
15+
16+
let kb2: KnowledgeBase = [
17+
.fact("foo", "bar"),
18+
.rule("foo", .var("y")) {
19+
.fact("foo", .var("y"))
20+
},
21+
.lit(12),
22+
.lit(14),
23+
]
24+
25+
let knowledge = Array(kb1 + kb2)
26+
XCTAssert(knowledge.contains(.fact("foo", "bar")))
27+
XCTAssert(knowledge.contains(.rule("foo", .var("x")) { .fact("foo", .var("x")) }))
28+
XCTAssert(knowledge.contains(.rule("foo", .var("y")) { .fact("foo", .var("y")) }))
29+
XCTAssert(knowledge.contains(.lit(12)))
30+
XCTAssert(knowledge.contains(.lit(13)))
31+
XCTAssert(knowledge.contains(.lit(14)))
32+
33+
XCTAssertEqual(knowledge.filter({ $0 == .fact("foo", "bar") }).count, 1)
34+
XCTAssertEqual(knowledge.filter({ $0 == .lit(12) }).count, 1)
35+
}
36+
37+
}

0 commit comments

Comments
 (0)