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

Ctypes Strings

2007-05-28

I've written bulk of PySWIP last summer, it is based on Nathan Denny's proolog.py. This is the first project that I used ctypes, a fantastic package which allows calling C functions from dynamic libraries that I use to link libpl.so (Linux) or libpl.dll (Windows) of SWI-Prolog. One of the dif­fi­cul­ties I had back then was finding the cor­re­spond­ing ctypes code for PL_get_chars which is defined at SWI-Prolog.h as follows:

PL_EXPORT(int) PL_get_chars(term_t t,
    char **s, unsigned int flags);

I use that function in queryGenerator:

answer = (c_char_p*maxsubresult)()
while PL_get_list(swipl_list, swipl_head, swipl_list):
    PL_get_chars(swipl_head, answer,
        CVT_ALL 
continue.

python, ctypes, prolog, pyswip

SEND + MORE + MONEY

2007-05-27

Finding valid and distinct integers for digits S, E, N, D, M, O, R and Y in the equation SEND + MORE = MONEY is a classical constraint pro­gram­ming problem. Here's the slightly modified version of the sample program at Wikipedia constraint pro­gram­ming entry for SWI-Prolog using clp library:

:- use_module(library('clp/bounds')).

sendmore(Digits) :-
   Digits = [S,E,N,D,M,O,R,Y],
   Digits in 0..9,
   S #\= 0,
   M #\= 0,
   all_different(Digits),
                1000*S + 100*E + 10*N + D
      
continue.

send more money, sendmory, constraint programming, prolog