Home > Back-end >  filling list with the same integer in prolog
filling list with the same integer in prolog

Time:08-30

I want to write a function that fill in the list with the same number on prolog. For example, I want the list [_,_,1,_] to be [1,1,1,1] or if the list is all empty [_,_,_,_] it will result in a number of my choice, 5 for example. Can anyone help me with that?

CodePudding user response:

:- use_module(library(clpfd)).

fill(Ls, Value) :-
    chain(Ls, #=),
    Ls = [Value|_].

e.g.

?- Ls = [_,_,1,_], fill(Ls, V).
Ls = [1, 1, 1, 1],
V = 1

?- Ls = [_,_,_,_], fill(Ls, 5).
Ls = [5, 5, 5, 5]

?- Ls = [_,_,1,_], fill(Ls, 7).
false

CodePudding user response:

Simple:

all(_,[],[]).
all(H,[H|T],[H|R]) :- all(H,T,R).

That gives me:

?- all(_,[_,_,1,_],Xs).
Xs = [1, 1, 1, 1].

?- all(5,[_,_,_,_],Xs).
Xs = [5, 5, 5, 5].

?- all(5,[_,_,1,_],Xs).
false.

?- all(_,[3,_,1,_],Xs).
false.
  • Related