一个最基本的尝试:创建一个名为switch.pl的文件。
:- module(switch, []).
compile_caselist(X, [K:Clause], (X = K -> Clause)) :- !.
compile_caselist(X, [K:Clause|CaseList], ((X = K -> Clause);Translated)) :-
compile_caselist(X, CaseList, Translated).
:- multifile user:goal_expansion/2.
user:goal_expansion(F, G) :-
F = switch(X, CaseList),
compile_caselist(X, CaseList, G).
然后像往常一样使用它:例如,在文件switch_test.pl中。
:- use_module(switch).
test1(X) :-
X = a -> writeln(case1) ;
X = b -> writeln(case2) ;
X = c -> writeln(case3).
test2(X) :-
switch(X, [
a : writeln(case1),
b : writeln(case2),
c : writeln(case3)
]).
编译 switch_test.pl 后:
?- listing(test2).
test2(A) :-
( A=a
-> writeln(case1)
; A=b
-> writeln(case2)
; A=c
-> writeln(case3)
).
true.
由于多次请求,这里提供一个编译模式来分离条款:
:- module(switch, []).
:- multifile user:term_expansion/2.
user:term_expansion((H:-B), [(H:-T)|SWs]) :-
collect_switches(H,B,T,SWs),
SWs \= [],
debug(switch, 'compiled <~w>~nto <~w>~nwith <~w>', [H,T,SWs]).
collect_switches(H,(A0;A),(B0;B),SWs) :-
collect_switches(H,A0,B0,S0),
collect_switches(H,A,B,S),
append(S0,S,SWs).
collect_switches(H,(A0,A),(B0,B),[S|SWs]) :-
call_switch(H,A0,B0,S), !,
collect_switches(H,A,B,SWs).
collect_switches(H,(A0,A),(A0,B),SWs) :-
collect_switches(H,A,B,SWs).
collect_switches(H,A,B,[S]) :-
call_switch(H,A,B,S), !.
collect_switches(_,C,C,[]).
call_switch(H,switch(X,CL),call(G,X),CTs) :-
functor(H,F,A),
R is random(1000000),
format(atom(G), '~s_~d_~d', [F,A,R]),
maplist({G}/[K:C,(H:-C)]>>(H=..[G,K]),CL,CTs).
现在测试脚本已经被封装在一个模块中,以便于进一步的列表显示:
:- module(switch_test, [test1/1,test2/1]).
:- use_module(switch).
test1(X) :-
X = a -> writeln(case1) ;
X = b -> writeln(case2) ;
X = c -> writeln(case3).
test2(X) :-
switch(X, [
a : writeln(case1),
b : writeln(case2),
c : writeln(case3)
]).
编译完switch_test.pl
后的结果如下:
?- switch_test:listing.
test1(A) :-
( A=a
-> writeln(case1)
; A=b
-> writeln(case2)
; A=c
-> writeln(case3)
).
test2(A) :-
call(test2_1_362716, A).
test2_1_362716(a) :-
writeln(case1).
test2_1_362716(b) :-
writeln(case2).
test2_1_362716(c) :-
writeln(case3).
为了方便调试:
?- debug(switch).
编译时输出如下的提示信息:
to <call(test2_1_362716,_G121946)>
with <[[(test2_1_362716(a):-writeln(case1)),(test2_1_362716(b):-writeln(case2)),(test2_1_362716(c):-writeln(case3))]]>
注意:这个草图显然需要更多的测试。
如果您决定对改进进行基准测试(如果有),请不要使用IO语句(例如writeln),因为那些会主宰执行时间。
term_expansion/2
和goal_expansion/2
。以在编译时重写术语。请参阅SWI-Prolog的apply_macros
库中的maplist/2
,了解如何将此类结构编译为辅助谓词的调用。 - mat