Michelle1243
Michelle1243

Reputation: 13

Prolog Lists, Add 1 to tail of the list

I'm trying to add either 1 or 2 to numbers in a list in SWI-Prolog.

I've managed to add 1 or 2 to the head of the list however I'm having difficulties adding onto each element on the tail of the list. I don't want to add 1 or 2 to EVERY element at the same time just at separate times. I.e. If my input is add([2,3,4], X).

I would like the possibilities of X to be the following: X = [3,3,4] X = [4,3,4] X = [2,4,4] X = [2,5,4] X = [2,3,5] X = [2,3,6]

My code at present is:

add([],[]).
add([H1|T1],[H2|T2]) :-
                    is(H2,+(H1,1)), T1=T2;
                    is(H2,+(H1,2)), T1=T2.

Obviously this only adds 1 or 2 onto the head of the list and not the tail. Therefore does anyone know how I may go about adding 1 or 2 onto the elements in the tail of my list?

Upvotes: 1

Views: 950

Answers (2)

CapelliC
CapelliC

Reputation: 60024

sometime more verbose can be clearer:

add([],[]).
add([H1|T],[H2|T]) :-
 H2 is H1+1.
add([H1|T],[H2|T]) :-
 H2 is H1+2.
add([H|T1],[H|T2]) :-
 add(T1,T2).

now alternatives are listed out, the last one just handles - recursively - the remaining elements

Anyway, your code is just missing a line:

add([],[]).
add([H1|T1],[H2|T2]) :-
 is(H2,+(H1,1)), T1=T2;
 is(H2,+(H1,2)), T1=T2;
 H1=H2, add(T1,T2).

After comment, here is how to subtract and keep only positive values:

add([H1|T1],[H2|T2]) :-
 H2 is H1-1, H2 > 0, T1=T2;
 ...

Upvotes: 0

Eugene Sh.
Eugene Sh.

Reputation: 18331

First define a predicate addX/3 that will add X to one of the members of the first list:

addX([], [],_).     % base case
addX([H|T], [H1 | T], X) :- H1 is H + X.   % add to first element
addX([H|T], [H | T1], X) :- addX(T, T1, X). % or retain the first element and add to some element in the tail

Than using it define your add predicate as addX with X=1 or X=2:

add(L, R) :- addX(L, R, 1).
add(L, R) :- addX(L, R, 2).

Testing:

?- add([2,3,4], X).
X = [3, 3, 4] ;
X = [2, 4, 4] ;
X = [2, 3, 5] ;
X = [2, 3, 4] ;
X = [4, 3, 4] ;
X = [2, 5, 4] ;
X = [2, 3, 6] ;
X = [2, 3, 4].

Upvotes: 1

Related Questions