Brill
Brill

Reputation: 63

creating a list in prolog based on an other list

i am a begginer in prolog and i want to write a code that creates a list based on another list.I wrote this :

create([_],N,J,K,J):- N>K.
create([X|Xs],N,L,K,J):- X==N , N1 is N + 1 , create(Xs,N1,[-1|L],K,J).
create([X|Xs],N,L,K,J):-N1 is N + 1 , create([X|Xs],N1,[0|L],K,J).

K is the size of the output list.
N is a counter .
L is the output.
X is the input list. 

?- create([1,2],1,[],5,N).
N = [0, 0, 0, 0, -1] 

i would like to get a list with size equal to 5(K) filled with zeros except the positions that are specified in the input list on which the value will be -1(I didnt reverse it).

Upvotes: 1

Views: 64

Answers (1)

CapelliC
CapelliC

Reputation: 60004

I think your code should be - note the list is built in the head, to avoid reversing)

create(_     ,N,K,    []) :- N > K, !.
create([N|Xs],N,K,[-1|L]) :- !, N1 is N + 1, create(Xs,N1,K,L).
create(   Xs ,N,K,[ 0|L]) :-    N1 is N + 1, create(Xs,N1,K,L).

It requires the zeros positions sorted. Otherwise, the more idiomatic - and cryptic -

create(Ps, N,K, L) :- findall(D, (
    between(N,K,P),
    ( memberchk(P,Ps) -> D = -1 ; D = 0)), L).

will work regardless the ordering.

Upvotes: 2

Related Questions