Easy replicate item in Prolog :)

I am working on a longer problem that allows me to duplicate an element N times in a list form, and I believe that using append is the right way to do this. A tiny predicate should theoretically act as follows:

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

I can not find any advice for this online, replication of one element, but I believe that we need to use append, but not a recursive solution. I come from a more Haskell background, where this problem will be much easier to implement. Can someone help me get started with this? :)

My:

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

What gives me:

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

Close, but not quite!

+4
source share
3 answers

. , . :

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

N , length(L, N) N "" ( ). maplist(=(X), L) L X.

, :

| ?- 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 0) - ?). :

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

: [X|T] - X N , .... , ? 0, , , repl N repl N-1. N > 0, . , , N , .

, "" , N:

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

...

length/2 , , o . N L , , 0. length(L, N). Prolog , .

+11

, :

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

, ; . x 5 , . , .

, , . , .

( , @lurker :-)) :

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

@lurker , , , .

/ . , ( , ).

%! 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).

, , . error SWI-Prolog. Prolog , .

PS: Haskell

, , Prolog, , Haskell, . , , , .

+3

findall/3 between/3 :

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

Source: https://habr.com/ru/post/1537246/


All Articles