在序言中减去或添加列表列表? [英] Subtracting or adding lists of lists in prolog?
问题描述
我对序言相当陌生,并试图弄乱列表清单.我很好奇如何添加两个列表列表或减去它们导致一个列表列表.如果我有两个列表,可以说
I am fairly new to prolog and am trying to mess around with lists of lists. I am curious on how to add two lists of lists or subtract them resulting in one list of list. If I have two lists of lists lets say,
SomeList = [[1,2,3,4],[5,6,7,8]]
SomeList2 = [[1,2,3,4],[5,6,7,8]]
如何添加或减去 SomeList
和 SomeList2
来创建列表列表?产生总和
How could I add or subtract SomeList
and SomeList2
to create a list of lists? Resulting in a sum of say
sumList([[2,4,6,8],[10,12,14,16]])
反之亦然?不寻求代码而是提供见识的任何帮助将不胜感激!
or vice-versa for subtraction? Any help would be appreciated not looking for code but for insight !
推荐答案
最简单的方法是使用 地图列表
:
The easiest approach is with maplist
:
add(X, Y, Z) :- Z is X + Y.
op_lists(L1, L2, R) :-
maplist(maplist(add), L1, L2, R).
哪个给:
| ?- op_lists([[1,2,3,4],[5,6,7,8]], [[1,2,3,4],[5,6,7,8]], R).
R = [[2,4,6,8],[10,12,14,16]]
yes
| ?-
在表达式中:
maplist(maplist(add), L1, L2, R).
maplist(G,L1,L2,R)
在 L1
和 L2
的每个元素上调用 G
,生成 R
的每个元素.由于 L1
和 L2
的每个元素都是一个列表,因此在这种情况下的 G
是 maplist(add)
在子列表的每个元素上调用 add
.
maplist(G, L1, L2, R)
calls G
on each element of L1
and L2
, resulting in each element of R
. Since each element of L1
and L2
is a list, then G
in this case is maplist(add)
which calls add
on each element of the sublists.
您显然可以将 add(X,Y,Z)
修改为您希望对每对元素进行的任何操作.您还可以使用CLP(FD)使添加的内容更加相关":
You can obviously modify add(X, Y, Z)
to be whatever operation you wish on each pair of elements. You can also make the addition more "relational" by using CLP(FD):
add(X, Y, Z) :- Z #= X + Y.
然后您还可以得到,例如:
Then you also get, for example:
| ?- op_lists([[1,2,3,4],[5,6,7,8]], L, [[3,6,9,12],[10,12,14,16]]).
L = [[2,4,6,8],[5,6,7,8]]
yes
| ?-
如果你想在没有 maplist
的情况下做到这一点,你仍然可以使用 add/3
并使用两层方法:
If you wanted to do this without maplist
, you could still use add/3
and use a two-layer approach:
op_lists([], [], []).
op_lists([LX|LXs], [LY|LYs], [LR|LRs]) :-
op_elements(LX, LY, LR),
op_lists(LXs, LYs, LRs).
op_elements([], [], []).
op_elements([X|Xs], [Y|Ys], [R|Rs]) :-
add(X, Y, R),
op_elements(Xs, Ys, Rs).
您可以在此处看到简单的列表处理模式,使用 maplist
可以帮您解决这个问题.
You can see the simple list processing pattern here, which the use of maplist
takes care of for you.
这篇关于在序言中减去或添加列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!