Yuce's Blog

Cognitive dissonance is yoga for the brain.*

PySWIP: Facts and Rules

2009-10-08

PySWIP is a Python module which enables accessing SWI-Prolog's foreign language interface using our beloved computer language. Here's a small tutorial on adding facts and rules to prolog knowl­edge­base.

First, adding facts and rules, based on examples in a Prolog tutorial.

from pyswip import Prolog
p = Prolog()

# something is fun if it is a car and it is red.
p.assertz('(fun(X) :- red(X), car(X))')

# facts...
p.assertz('car(vw_beatle)')
p.assertz('car(ferrari)')
p.assertz('car(hyundai)')
p.assertz('bike(harley_davidson)')
p.assertz('red(ferrari)')
p.assertz('red(vw_beatle)')
p.assertz('blue(hyundai)')

Find all cars in the knowl­edge­base:

print list(p.query('car(Which)'))

Outputs:

[{'Which':'vw_beatle'}, {'Which':'ferrari'}, {'Which':'hyundai'}]

Find all fun things:

print list(p.query('fun(What)'))

Outputs:

[{'What':'vw_beatle'}, {'What':'ferrari'}]

Pretty easy, huh? ;) There are more complex Prolog examples in PySWIP source dis­tri­b­u­tion, including a sudoku solver.

python, prolog, pyswip

comments powered by Disqus