Prolog - 将列表转换为事实列表

时间:2018-01-21 21:00:30

标签: python-3.x prolog swi-prolog

我用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).

我需要在以下列表中解析输入参数“cbbaa 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的专家,我现在真的被困住了,我希望有人可以帮助我。提前谢谢。

1 个答案:

答案 0 :(得分:1)

你快到了:

auto &move_from_var = char_to_var(move_from);
auto &move_to_var = char_to_var(move_to);
move_to_var += move_from_var;
move_from_var = 0; 

保存在名为:- 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). 的文件中后,我会得到以下结果:

$ swipl argv.pl a b c d
Called with [on(a,b),on(c,d)]

也就是说,已经实现了参数对,并且'程序'终止了。 没有错误处理,传递奇数个参数,我收到警告:

$ swipl argv.pl a b c
Warning: /home/carlo/test/prolog/argv.pl:1: Initialization goal failed
Welcome to SWI-Prolog (threaded, 64 bits, version 7.7.7-2-gd842bce)
etc etc...

无论如何,我认为您的argv.pl在成功解析/ 2后应该main然后retractall(on(_,_))