简体   繁体   English

如何在SWI序言中重复该列表?

[英]How Can I repeat the list in swi prolog?

How Can I repeat the list in swi prolog? 如何在SWI序言中重复该列表?

{ex: repeat(X,Y,N) to be true when Y is the list consisting of each element of X repeated N times (eg repeat([a,b], [a,a,a,b,b,b],3) is true). {例如:当Y是由X个元素重复N次组成的列表时(例如repeat([a,b],[a,a,a,b,b,b ],3)是正确的。 } }

In haskell ... 在haskell ...

rep ls n = [i | rep ls n = [i | i<- ls, _ <- [1 .. n]] main = print $ rep ["1","2"] 3 i <-ls,_ <-[1 .. n]] main =打印$ rep [“ 1”,“ 2”] 3

In prolog 前言

:- forall(I,between(1,3),Ls),Ls=[1,2,3]. :-forall(I,between(1,3),Ls),Ls = [1,2,3]。

The trick here is to have nested iterations - iteration over N..1 nested into the iteration over the elements of the original list. 这里的技巧是具有嵌套的迭代-将N..1的迭代嵌套到原始列表元素之上的迭代中。 This works in SWI-Prolog: repeat_list([],[],_) :- !. 这在SWI-Prolog中有效:repeat_list([],[],_):-!。

repeat_list(_,[],0) :- !.

repeat_list(X,Y,N) :-
    N > 0,
    repeat_list(N,N,X,Y),
    !.

repeat_list(_,_,[],[]) :- !.

repeat_list(1,N,[H|List1],[H|List2]) :-
    repeat_list(N,N,List1,List2).

repeat_list(M,N,[H|List1],[H|List2]) :-
    L is M - 1,
    repeat_list(L,N,[H|List1],List2).

NB Try not to use standard clause names such as repeat for purposes different from what standard intends to use it for. NB尽量不要使用标准条款名称,如repeat的目的,从什么标准打算用它来做不同。

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

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