# 在Prolog中轻松复制元素:)Easily replicate an element in Prolog :)

``````?- repl(x,5,L).
L = [x, x, x, x, x] ;
false.
``````

``````repl(E, N, R) :-
N > 0, append([E], [], R), writeln(R), repl(E, N-1, R), fail.
``````

``````?- repl(x,5,L).
[x]
[x]
[x]
[x]
[x]
false.
``````

## 3 个回复3

### ===============>>#1 票数：11 已采纳

``````repl(X, N, L) :-
length(L, N),
maplist(=(X), L).
``````

``````| ?- repl(X, N, L).

L = []
N = 0 ? ;

L = [X]
N = 1 ? ;

L = [X,X]
N = 2 ? ;
| ?- repl(X, N, [x,x,x]).

N = 3
X = x

yes
...
``````

``````repl(X, N, [X|T]) :- ...
``````

``````repl(X, N, L) :-
length(L, N),
simple_recursive_repl(X, N, L).

...
``````

### 确定性

``````?- repl(x,5,L).
L = [x, x, x, x, x] ;
false.
``````

### 重复清单

``````repeating_list(_, 0, []):- !.
repeating_list(H, Reps1, [H|T]):-
Reps2 is Reps1 - 1,
repeating_list(H, Reps2, T).
``````

### 一些扩展

``````%! repeating_list(+Term:term, +Repeats:integer, -List:list(term)) is det.
%! repeating_list(?Term:term, ?Repeats:integer, +List:list(term)) is det.

repeating_list(_, 0, []):- !.
% The term and number of repetitions are known given the list.
repeating_list(H, Reps, L):-
nonvar(L), !,
L = [H|T],
forall(
member(X, T),
% ==/2, since `[a,X]` does not contain 2 repetitions of `a`.
X == H
),
length([H|T], Reps).
% Repetitions is given, then we generate the list.
repeating_list(H, Reps1, [H|T]):-
must_be(nonneg, Reps1), !,
Reps2 is Reps1 - 1,
repeating_list(H, Reps2, T).
% Repetitions is not `nonneg`.
repeating_list(_, Reps, _):-
domain_error(nonneg, Reps).
``````

``````repl(E, N, L) :- findall(E, between(1, N, _), L).