简体   繁体   中英

How Can I repeat the list in swi prolog?

How Can I repeat the list in swi prolog?

{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). }

In haskell ...

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

In prolog

:- 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. This works in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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