我在Python中启动SWI-prolog,使用以下命令:
subprocess.call("(source ~/.bash_profile && swipl -s planner.pl b a c b a table )", shell=True)
启动的脚本是一个计划器:
:- initialization (main).
:- dynamic on/2.
%facts
on(a,b).
on(b,c).
on(c,table).
r_put_on(A,B) :-
on(A,B).
r_put_on(A,B) :-
not(on(A,B)),
A == table,
A == B,
clear_off(A),
clear_off(B),
on(A,X),
retract(on(A,X)),
assert(on(A,B)),
assert(move(A,X,B)).
% Means there is space on table
clear_off(table).
% Means already clear
clear_off(A) :- not(on(_X,A)).
clear_off(A) :-
A == table,
on(X,A),
clear_off(X),
retract(on(X,A)),
assert(on(X,table)),
assert(move(X,A,table)).
do(Glist) :-
valid(Glist),
do_all(Glist,Glist).
valid(_).
do_all([G|R],Allgoals) :-
call(G),
do_all(R,Allgoals),!.
do_all([G|_],Allgoals) :-
achieve(G),
do_all(Allgoals,Allgoals).
do_all([],_Allgoals).
achieve(on(A,B)) :-
r_put_on(A,B).
main :-
current_prolog_flag(argv, Argv),
format('Called with ~q~n', [Argv]),
parse the list
listing(on), listing(move),
halt.
main :-
halt(1).
我需要解析输入参数"c b b a a table"列表中的:"[on(c,b(,on(b,a(,on(a,table(]",以便从规则执行(例如do([on(c,b(,on(b,a(,on(a,table(]((。格式打印我这个:Called with [on,b,a,c,b,a,table]
不是Prolog的专家,我现在真的很困,希望有人可以帮助我。提前谢谢你。
你快到了:
:- initialization (main).
main :-
current_prolog_flag(argv, Argv),
parse(Argv, Parsed),
format('Called with ~q~n', [Parsed]),
halt(1).
parse([], []).
parse([X,Y|Argv], [on(X,Y)|Parsed]) :- parse(Argv, Parsed).
一旦保存在名为 argv.pl
的文件中,我就会得到以下结果:
$ swipl argv.pl a b c d使用 [on(a,b(,on(c,d(] 调用
也就是说,参数对已经实现,"程序"终止了。没有错误处理,传递奇数个参数,我收到警告:
$ swipl argv.pl a b c警告:/home/carlo/test/prolog/argv.pl:1:初始化目标失败欢迎来到SWI-Prolog(线程,64位,版本7.7.7-2-gd842bce(等等等等...
无论如何,我认为您的main
,在成功解析/2之后,应该retractall(on(_,_))
然后maplist(assertz,Parsed)
.