appendAll-将列表追加到列表中的所有列表 [英] appendAll - Append a list to all lists within a list

查看:144
本文介绍了appendAll-将列表追加到列表中的所有列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种将列表追加到列表中所有列表的方法.

I'm trying to find a way to append a list to all lists within a list.

类似的东西:

appendAll([a,b],[[q,w],[z,x]],X).
X = [[a,b,q,w],[a,b,z,x]].

我仍然对序言还不陌生,并且嵌套列表使我大吃一惊.

I'm still new to prolog and nested lists are throwing me off quite a bit.

我已经盯着这个看了几个小时了:

I've been staring at this for a few hours now:

appendAll([], _, []).
appendAll(_, [], []).
appendAll([H1|T1], [H2|T2], X) :-
  append(H1,H2,R),
  appendAll(T1,[H2|T2],X).
  % recurse down to [], and append back up

非常感谢您的帮助!

推荐答案

使用Prolog进行编程的困难在于习惯并识别背后的实际递归模式.在许多情况下,最好不要直接考虑递归,而要问一下所有构造简单的方法在这里是否可行.

What is difficult in programming with Prolog is to get used to and identify the actual recursion patterns behind. In many cases it is best not to think in recursions directly, but rather ask if some simple for all construct might work here.

在这种情况下,您需要一个列表列表和另一个列表列表之间的关系.两者的长度相同,因为元素在元素方面彼此对应.

In this case, you want a relation between a list of lists and another list of lists. Both are of same length, as the elements correspond to each other element-wise.

appendAll(Prefix, Lists, Prefixedlists) :-
    maplist(append(Prefix), Lists, Prefixedlists).

谓词maplist/3在许多Prolog系统中定义.如果没有,请在符合ISO的系统中这样定义它:

The predicate maplist/3 is defined in many Prolog systems. If not, define it like so in an ISO conforming system:

maplist(_Cont_2, [], []).
maplist(Cont_2, [X|Xs], [Y|Ys]) :-
   call(Cont_2, X, Y),
   maplist(Cont_2, Xs, Ys).

这里与普通谓词相同:

maplist_append(Prefix, [], []).
maplist_append(Prefix, [X|Xs], [Y|Ys]) :-
   append(Prefix, X, Y),
   maplist_append(Prefix, Xs, Ys).

这篇关于appendAll-将列表追加到列表中的所有列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆