拼接列表中的子列表,而不使用flatten/2 [英] Splice in sublists in a list, without using flatten/2

查看:82
本文介绍了拼接列表中的子列表,而不使用flatten/2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用Prolog中使用 flatten 谓词的情况下,将多个子列表做成一个列表.

I want to make one list of multiple sublists without using the flatten predicate in Prolog.

这是我的代码:

acclistsFromList([],A,A).
acclistsFromList([H|T],Listwithinlist,A):-
  not(is_list(H)), 
  acclistsFromList(T,Listwithinlist,A).
acclistsFromList([H|T],Listwithinlist,A):-
  is_list(H), 
  append([H],Listwithinlist,Acc2), 
  acclistsFromList(T,Acc2,A).

我得到这个作为输出

?- listsFromList([1,2,[a,b,c],3,4,[d,e]],X). 
X = [[d, e], [a, b, c]] ;

但是我想要这个:

?- listsFromList([1,2,[a,b,c],3,4,[d,e]],X).
X = [a, b, c, d, e] .

?- listsFromList([1,[],2,3,4,[a,b]],X).
X = [a, b] .

?- listsFromList([[[[a]]],b,c,d,e,[f]],X).
X = [f, a] .

?- listsFromList([[[[a]],b,[c]],d,e,[f]],X).
X = [f, a, b, c] .

在不使用 flatten 的情况下达到此结果的最佳方法是什么?

What is the best way to reach this result, without using flatten?

推荐答案

acclistsFromList/3 的第二个子句如果已验证 H 则不执行任何操作 H 不是列表,但是您需要在结果前添加 H .

The second clause of the acclistsFromList/3 does not do anything with H if it has verified that H is not a list, but you need to prepend the result with H.

acclistsFromList([H|T], Listwithinlist, [H|A]) :-
    \+ is_list(H),
    acclistsFromList(T, Listwithinlist, A).

但这还不够.由于您位于累加器之前,因此结果相反.无论如何,您这里不需要蓄能器:

but this is not sufficient. Since you prepend to the accumulator, the result is reversed. You do not need an accumulator here anyway:

acclistsFromList([], []).
acclistsFromList([H|T], [H|A]) :-
    \+ is_list(H),
    acclistsFromList(T, A).
acclistsFromList([H|T], Result):-
    is_list(H),
    append(H, Res1, Result),
    acclistsFromList(T, Res1).

或没有标量"元素:

acclistsFromList([], []).
acclistsFromList([H|T], A) :-
    \+ is_list(H),
    acclistsFromList(T, A).
acclistsFromList([H|T], Result):-
    is_list(H),
    append(H, Res1, Result),
    acclistsFromList(T, Res1).

此外,这不会在列表上递归.因此,列表的列表列表将不会被展平.我将其保留为实现此目的的练习.

This furthermore does not recurse on lists. A list of lists of lists will thus not be flattened. I leave it as an exercise to implement this.

这篇关于拼接列表中的子列表,而不使用flatten/2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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