Prolog:交换列表的两半 [英] Prolog: Swapping two halves of a list
问题描述
我正在 prolog 中编写一个谓词,它将具有偶数个变量的列表分成两半并交换它们.例如 [a,b,c,d] --> [c,d,a,b].
append([], List, List).追加([头|尾],列表,[头|休息]):-追加(尾部,列表,休息).除(L,X,Y): -追加(X,Y,L),长度(X,N),长度(Y,N).交换([], []).交换([A],D): -除(A,B,C),追加(C,B,D).
我希望通过将 [A] 分成两个大小相等的较小列表,然后以相反的顺序将它们附加在一起,然后将变量D"分配给列表来实现这一点.
我得到的是假",为什么这不起作用?
我对 prolog 很陌生,所以这可能是一个愚蠢/简单的问题,谢谢!
你的问题是为什么 swap([a,b,c,d],[c,d,a,b])
失败.这是真正的原因:
因此,不仅您的原始查询失败,而且即使是这种泛化也失败了.即使你问
?- 交换([_,_|_],_).错误的.
你只会失败.看到了吗?
你也可以反过来问.有了上面的概括,我们可以问:
?- 交换(Xs,Ys).Xs = [];Xs = [_A].
所以你的第一个参数必须是空列表或只有一个元素的列表.您当然还想描述更长的列表.
I am writing a predicate in prolog that will break a list with an even number of variables into two halves and swap them. For example [a,b,c,d] --> [c,d,a,b].
append([], List, List).
append([Head|Tail], List, [Head|Rest]) :-
append(Tail, List, Rest).
divide(L, X, Y) :-
append(X, Y, L),
length(X, N),
length(Y, N).
swap([], []).
swap([A], D) :-
divide(A, B, C),
append(C, B, D).
I would expect this to work by dividing [A] into two smaller equal sized lists, then appending them together in the reverse order, and then assigning the variable "D" to the list.
What I am getting is "false", why does this not work?
I'm very new to prolog so this might be a silly/simple question, thanks!
Your question is why swap([a,b,c,d],[c,d,a,b])
fails. And here is the actual reason:
?- swap([_/*a*/,_/*b*/|_/*,c,d*/],_/*[c,d,a,b]*/). :- op(950, fy, *). *(_). swap([], _/*[]*/). swap([A], D) :- *divide(A, B, C), *append(C, B, D).
So, not only does your original query fail, but even this generalization fails as well. Even if you ask
?- swap([_,_|_],_).
false.
you just get failure. See it?
And you can ask it also the other way round. With above generalization, we can ask:
?- swap(Xs, Ys).
Xs = []
; Xs = [_A].
So your first argument must be the empty list or a one-element list only. You certainly want to describe also longer lists.
这篇关于Prolog:交换列表的两半的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!