File tree 2 files changed +41
-3
lines changed
2 files changed +41
-3
lines changed Original file line number Diff line number Diff line change @@ -95,10 +95,11 @@ public struct KnowledgeBase: Hashable {
95
95
96
96
public static func + ( lhs: KnowledgeBase , rhs: KnowledgeBase ) -> KnowledgeBase {
97
97
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 ] ?? [ ]
100
100
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) } ) )
102
103
}
103
104
}
104
105
result. literals = lhs. literals. union ( rhs. literals)
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments