1 from logic import KB
2 from pyxf import swipl
3
5 '''SWI Prolog knowledge base'''
6 - def __init__( self, sentence=None, path='swipl' ):
7 '''Constructor method
8 Usage: SWIKB( sentence, path )
9 sentence - Prolog sentence to be added to the KB (default: None)
10 path - path to SWI Prolog executable (default: 'swipl')'''
11 self.swi = swipl( path )
12 if sentence:
13 self.tell( sentence )
14
15 - def tell( self, sentence ):
16 '''Adds sentence to KB'''
17 sentence = sentence.strip()
18 if sentence[ -1 ] == '.':
19 sentence = sentence[ :-1 ]
20 return self.swi.query( 'assert(' + sentence + ')' )
21
22 - def ask( self, query ):
23 '''Queries the KB'''
24 return self.swi.query( query )
25
27 '''Deletes sentence from KB'''
28 sentence = sentence.strip()
29 if sentence[ -1 ] == '.':
30 sentence = sentence[ :-1 ]
31 return self.swi.query( 'retract(' + sentence + ')' )
32
34 '''Loads module to KB
35 Usage: instance.loadModule( path )
36 path - path to module'''
37 self.swi.load( module )
38
39 if __name__ == '__main__':
40 kb = SWIKB()
41 kb.tell( 'a(b,c)' )
42 kb.tell( 'a(c,d)' )
43 kb.tell( '( p(_X,_Y) :- a(_X,_Y) )' )
44 kb.tell( '( p(_X,_Y) :- a(_X,_Z), p(_Z,_Y) )' )
45 for result in kb.ask( 'p(X,Y)' ):
46 print result
47 kb.retract( 'a(b,c)' )
48