1
votes

I am trying to implement a recursive Prolog predicate that when given a all 0 list ResultList with Dim elements and another list with values up to Dim, it runs trough this second list and increments +1 to the nth Element of ResultList and returns ResultList, so far I have:

increment_list([],_).
increment_list([Element|Tail],ResultList):-
    nth1(Element,ResultList,_ is _+1),
    increment_list(Tail,ResultList).

So for example

?-increment_list([1,2,4,3,4],[0,0,0,0]).

Would return:

[1,1,1,2]

What I'm apparently having difficulty and confusion is how to increment the value, is it possible to do it without defining an extra predicate or having a singleton Variable?

1
No, it isn't possible to do it without defining an extra predicate, although the lambda library probably would make it easier. The idea of sticking _ is _+1 inside a call to nth1/3 is definitely not going to work. Remember that Prolog is going to unify these values, not compute them; is/2 will perform arithmetic, but this expression wouldn't make sense much of anywhere because you are discarding the result of the addition. Also keep in mind Prolog is not going to evaluate expressions in-place. This is a core difference of Prolog. - Daniel Lyons

1 Answers

3
votes

In prolog you cannot modify the value inside a list. You can do something like this:

increment_list([],L,L).
increment_list([H|T],LT,LO):-
    increment_nth(H,1,LT,LT1),
    increment_list(T,LT1,LO).

increment_nth(_,_,[],[]).
increment_nth(I,I,[H1|T1],[H2|T1]):-!, 
    succ(H1,H2).
increment_nth(I,C,[H|T1],[H|T2]):-
    C1 is C+1,
    increment_nth(I,C1,T1,T2).

Is basically a nested loop. In each loop you create a new list, which is the same previous list except the value at the index you consider which is the previous index incremented by one.

?- increment_list([1,2,4,3,4,1],[0,0,0,0],LO).
LO = [2, 1, 1, 2]

EDIT

Thanks to Daniel Lyons, i've modified the predicate.