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?
This is the solution