(compiler: SWI Prolog )
In the numerical list, replace all occurrences of positive values ​​with negative elements of the same list, passing the list in order. Example.

 ?-replace_positive([1,-2, 3, -4, -5, 6, 7, 8], X) X = [-2, -2, -4, -4, -5, -5, 'No', 'No'] 

I tried something like that, backtracking one step back, but something doesn't work

  replace_positive([H|T],LN,[H1|R]):- (H < 0), H1 = H, LN1 = H, replace_positive(T, LN1, R), H is LN1. 
  • @shkiper; To format a code, select it with the mouse and click on the {} button of the editor. - ReinRaus
  • I understand, I will correct - shkiper
  • @alexlz, If it is less than zero, then as it is, otherwise we take from the second list, if it ends then It's all good. why not make it the answer? - vkovalchuk88 pm
  • one
    A small addition. In the answer. - alexlz

1 answer 1

@shkiper can it?

 t1([], [], []). t1([X|Y], [X|Z], Q) :- X > 0, t1(Y, Z, Q). t1([X|Y], Z, [X|Q]) :- X =< 0, t1(Y, Z, Q). t2([], [], _, []). t2([XH|XT], Y, Z, [XH|QT]) :- XH < 0, t2(XT, Y, Z, QT). t2([XH|XT], [XH|YT], [ZH|ZT], [ZH|QT]) :- t2(XT, YT, ZT, QT). t2([XH|XT], YT, [XH|ZT], [XH|QT]) :- t2(XT, YT, ZT, QT). t2([XH|XT], [XH|YT], [], ['No'|QT]) :- t2(XT, YT, [], QT). replace_positive(X, Q) :- t1(X, Y, Z), t2(X, Y, Z, Q). 

UPD The search for a list of positive values ​​is superfluous, therefore:

 t1([], []). t1([X|Y], Q) :- X > 0, t1(Y, Q). t1([X|Y], [X|Q]) :- X =< 0, t1(Y, Q). t2([], _, []). t2([XH|XT], Z, [XH|QT]) :- XH < 0 -> t2(XT, Z, QT). t2([XH|XT], [ZH|ZT], [ZH|QT]) :- XH >= 0 -> t2(XT, ZT, QT). t2([XH|XT], [], ['No'|QT]) :- XH > 0 -> t2(XT, [], QT). replace_positive(X, Q) :- t1(X, Z) -> t2(X, Z, Q).