简体   繁体   English

Prolog在列表列表中转换列表

[英]Prolog Convert a list in a list of lists

I need to convert a list of elements into a list of lists. 我需要将元素列表转换为列表列表。 For example, if i have the list [1,2,3,4] the output must be [[1],[2],[3],[4]], one element per list. 例如,如果我有列表[1,2,3,4],则输出必须为[[1],[2],[3],[4]],每个列表一个元素。

create([],_, _, _).
create([H|T], Aux, X, Result) :-
   append([H], Aux, X),
   Result = [X],
   create(T, X, _, Result).

I always get false... is this even possible to do? 我总是假的...这甚至可能做到吗?

Another possibility to define this relation is by using DCGs. 定义此关系的另一种可能性是使用DCG。 They yield easily readable code when describing lists. 描述列表时,它们产生易于阅读的代码。 Let's stick with the name singletons as suggested by @false in the comments: 让我们继续使用@false在注释中建议的名称singletons:

singletons([]) -->        % the empty list
   [].                    % is empty
singletons([H|T]) -->     % the head of a nonempty list
   [[H]],                 % is a list on its own
   singletons(T).         % and so is the tail

You can query this directly with phrase/2: 您可以直接用词组/ 2进行查询:

   ?- phrase(singletons([1,2,3,4]),X).
X = [[1],[2],[3],[4]]

Or write a wrapper-predicate with phrase/2 as the single goal: 或写一个带有短语/ 2作为单个目标的包装谓词:

singletons(L,Ls) :-
   phrase(singletons(L),Ls).

And query that: 并查询:

   ?- singletons([1,2,3,4],Ls).
Ls = [[1],[2],[3],[4]]

The predicate also works the other way around: 谓词也可以以其他方式工作:

   ?- singletons(L,[[1],[2],[3],[4]]).
L = [1,2,3,4] ? ;
no

As well as the most general query: 以及最一般的查询:

   ?- singletons(L,Ls).
L = Ls = [] ? ;
L = [_A],
Ls = [[_A]] ? ;
L = [_A,_B],
Ls = [[_A],[_B]] ?
...

Alternatively you can also define a simple predicate that describes a relation between an arbitrary element and itself in brackets and then use maplist/3 from library(apply) to apply it on every element of a list: 另外,您还可以定义一个简单的谓词,该谓词在方括号中描述任意元素与其自身之间的关系,然后使用library(apply)中的maplist / 3将其应用于列表的每个元素:

:- use_module(library(apply)).

embraced(X,[X]).

singletons(L,Ls) :-
   maplist(embraced,L,Ls).

This version yields the same results for the above queries. 对于上述查询,此版本产生相同的结果。 However, it is more efficient. 但是,它效率更高。 To see that consider the following query from above: 要查看该信息,请考虑上面的以下查询:

   ?- singletons(L,[[1],[2],[3],[4]]).
L = [1,2,3,4]

Above you had to enter ; 在上面你必须进入; to make Prolog search for further solutions and subsequently fail (indicated by no ). 使Prolog搜索其他解决方案,随后失败(用no表示)。 With this version there are no unnecessary choice points left and Prolog is succeeding deterministically for the query. 在此版本中,没有多余的选择点,并且Prolog可确定地成功进行查询。

Try this 尝试这个

create([],[]).

create([H|T],[[H]|T2]):- create(T,T2).

I tried 我试过了

?- create([1,2,3,4],X).

and the result was 结果是

X = [[1], [2], [3], [4]].

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM