对于河内之塔,输出应该如下:
?-move(3,[1,2,3],[],[],A1,B1,C).
A1=[].
B1=[1,2,3]
C=[].
我知道怎么做:
move(1,[H|T],B,C,A1,B1,C) :-
A1 = T,
B1 = [H|B],
C1 = C.
move(N,A,B,C,A1,B1,C) :-
N>1,
M is N-1,
move(M,[H|T],C,B,A1,B1,C),
move(1,[H|T],B,_,A1,B1,C),
move(M,C,B,[H|T],A1,B1,C).
但接下来的问题是: “改写程序,以便在每次搬家后提供塔楼的插图”。它的输出应该如下所示:
?- move(3,tower(a,[1,2,3]),tower(b,[]),tower(c,[]),A,B,C).
a[2 3] b[1] C[]
a[3] b[1] C[2]
a[3] b[] C[1 2]
a[] b[3] C[1 2]
a[1] b[3] C[2]
a[1] b[2 3] C[]
a[] b[1 2 3] C[]
A = tower(a, [])
B = tower(b,[1, 2, 3])
C = tower(c,[])
如何做到这一点?
答案 0 :(得分:1)
您可以使用以下谓词打印以空格分隔的列表:
write_list_([]) :- write(']').
write_list_([X|Xs]) :- write(' '), write(X), write_list_(Xs).
write_list([]) :- write('[]').
write_list([X|Xs]) :- write('['), write(X), write_list_(Xs).