Replace first K occurrences of 1 with any number say 8 in a list in Prolog

125 Views Asked by At

Replace the first K occurrences of a number with any other number. Considering 1 to be replaced by 8 in here.

This is how my predicate would look like

 replace_first_k(3,[1,2,3,1,1,5,6,1,7],X).

It should give the following output -

E = [8,2,3,8,8,5,6,1,7]

This is the code I have written so far

replace(0,[], []).
replace(0,L,L).
replace(X,[H|T], Res) :-

     ( X > 0 , 1 \== H -> replace(X1,T, Res1) , Res = [H|Res1] 

    ; 1 == H,X1 is X - 1, replace(X1,T, Res1),  Res = [8|Res1] ).

It seems to be working only when my first X occurrences are 1. Can someone tell me what is wrong here?

1

There are 1 best solutions below

0
On
replace(X,[], []).
replace(0,L,L).
replace(X,[H|T], Res) :-

     ( X > 0 , 1 \== H -> replace(X,T, Res1) , Res = [H|Res1] 

    ; 1 == H,X1 is X - 1, replace(X1,T, Res1),  Res = [8|Res1] ).

This is the solution