From b6a2938043d1ad4d7587db361fcefea4d4d14ee1 Mon Sep 17 00:00:00 2001 From: Timotej Lazar Date: Thu, 7 May 2015 11:17:37 +0200 Subject: Merge prolog.engine.create{,_and_ask} functions --- prolog/engine.py | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) (limited to 'prolog') diff --git a/prolog/engine.py b/prolog/engine.py index 6215bb2..50282d4 100644 --- a/prolog/engine.py +++ b/prolog/engine.py @@ -6,27 +6,22 @@ import json import re import urllib -# Create a new pengine, initialize it with [code] and return its ID. The engine -# will be destroyed after completing one query. -def create(code=''): +# Create a new pengine, initialize it with [code] and return Prolog's reply. +# The engine is destroyed after answering one query. If [query] is given, the +# first answer is returned and the engine destroyed. +def create(code='', query=''): opts = {'format': 'json-s', 'destroy': True, 'src_text': code} + if query: + opts['ask'] = query reply, messages = request('POST', '/pengine/create', body=json.dumps(opts)) if reply.get('event') != 'create' or 'error' in messages: raise Exception('\n'.join(messages['error'])) - return reply['id'] - -# Create a new pengine with [code], run [query] and destroy the engine. Return -# the reply from engine. -def create_and_ask(code, query): - opts = {'format': 'json-s', 'destroy': True, 'src_text': code, 'ask': query} - reply, messages = request('POST', '/pengine/create', body=json.dumps(opts)) - - if reply.get('event') != 'create' or 'error' in messages: - raise Exception('\n'.join(messages['error'])) - - return reply['answer']['data'] + # If query was given, the actual reply is nested in create/destroy objects. + if query: + reply = reply['answer']['data'] + return reply def ask(engine, query): return send(engine, 'ask(({}),[])'.format(query)) @@ -107,7 +102,7 @@ def get_message(reply): # Basic sanity check. if __name__ == '__main__': - engine = create(code='dup([],[]). dup([H|T],[H,H|TT]) :- dup(T,TT).') + engine = create(code='dup([],[]). dup([H|T],[H,H|TT]) :- dup(T,TT).')['id'] print('engine id is ' + engine) print(ask(engine, "run_tests({}, Result)".format('dup/2'))) destroy(engine) -- cgit v1.2.1