谓词解压缩列表 [英] Predicate to unzip a list
问题描述
List1=[(x,1),(y,1),(z,1)]
我正在尝试拆分此列表:
I'm attempting to split this list:
分为两个列表:
List3=[x,y,z]
List4=[1,1,1]
所以我写了这个谓词来尝试做到这一点:
So I have written this predicate to try to do it:
splt([], [], []).
splt([X|Xs], [Y|Ys], [X,Y|Zs]) :-
splt(Xs,Ys,Zs).
但是,谓词返回的不是预期的结果:
However instead of the desired result, the predicate returns:
1 ?- splt([(x,1),(y,2),(z,3)],L3,L4).
L3 = [_G1760, _G1769, _G1778],
L4 = [ (z, 1), _G1760, (y, 2), _G1769, (z, 3), _G1778].
推荐答案
首先,您选择的术语.这:(a, b)
,绝对不是,您通常会在Prolog中表示元组".您几乎总是将a-b
用作对",并且在整个标准库中都使用了对.
First, the term you have chosen. This: (a, b)
, is most definitely not how you would usually represent a "tuple" in Prolog. You almost always use a-b
for a "pair", and pairs are used throughout the standard libraries.
因此您的初始列表如下所示:[x-1, y-1, z-1]
.
So your initial list would look like this: [x-1, y-1, z-1]
.
这也应该解释为什么您遇到问题.您编写了(a, b)
,但是您的谓词为a, b
,并且当您希望获得一个,(a,b)
术语时会消耗两个元素.因此,要修正您当前的谓词,您可以编写:
This should also explain why you are having your problem. You write (a, b)
, but your predicate says a, b
, and you consume two elements when you expect to get one ,(a,b)
term. So, to fix your current predicate you would write:
split([], [], []).
split([X|Xs], [Y|Ys], [(X,Y)|XYs]) :-
split(Xs, Ys, XYs).
?- split(Xs, Ys, [(x,1), (y,1), (z,1)]).
Xs = [x, y, z],
Ys = [1, 1, 1].
但是,使用更常规的名称,术语顺序和Prolog对:
But instead, using a more conventional name, term order, and Prolog pairs:
zip([], [], []).
zip([X-Y|XYs], [X|Xs], [Y|Ys]) :-
zip(XYs, Xs, Ys).
?- zip([x-1, y-1, z-1], Xs, Ys).
Xs = [x, y, z],
Ys = [1, 1, 1].
当然,SWI-Prolog至少具有库(对),并且它带有pairs_keys_values/3
:
And of course, SWI-Prolog at least has a library(pairs), and it comes with a pairs_keys_values/3
:
?- pairs_keys_values([x-1, y-1, z-1], Xs, Ys).
Xs = [x, y, z],
Ys = [1, 1, 1].
这篇关于谓词解压缩列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!