I've developed a predicate which replaces the value of the index Index
of a list List
with Value
and creates a new updated list NewList
.
%replace(List,Index,Value,NewList)
replace([_|T], 0, X, [X|T]).
replace([H|T], I, X, [H|R]):-
I > -1,
NI is I-1,
replace(T, NI, X, R), !.
replace(L, _, _, L).
The predicate works fine on regular lists, but I want to make it work on a list of lists and I am kind of stuck on a little step.
subs([]).
subs([Head|Tail], Index) :-
replace((Head), Index, 'r', Board2),
printRow(Board2),
subs(Tail).
Original List:
[ [ 0 , 1 , 2 , 3 , 4 ] ,
[ 5 , 6 , 7 , 8 , 9 ] ,
[ 10 , 11 , 12 , 13 , 14 ] ,
[ 15 , 16 , 17 , 18 , 19 ] ,
[ 20 , 21 , 22 , 23 , 23 ]
]
Output:
[ [ 0 , r , 2 , 3 , 4 ] ,
[ 5 , r , 7 , 8 , 9 ] ,
[ 10 , r , 12 , 13 , 14 ] ,
[ 15 , r , 17 , 18 , 19 ] ,
[ 20 , r , 22 , 23 , 23 ]
]
It is noticeable why this happens, since it replaces the value with Index = 1
on each sublist.
In order to fix it, I thought about implementing a counter. By incrementing the index by 5 each iteration (size of each sub list), the predicate should now output the following (desired) list:
Desired Output:
[ [ 0 , r , 2 , 3 , 4 ] ,
[ 5 , 6 , 7 , 8 , 9 ] ,
[ 10 , 11 , 12 , 13 , 14 ] ,
[ 15 , 16 , 17 , 18 , 19 ] ,
[ 20 , 21 , 22 , 23 , 23 ]
]
And the issue lies on how to implement that very counter. The code should look like the following but there's something I'm missing out on:
subs([]).
subs([Head|Tail], Index) :-
replace((Head), Index, 'r', Board2),
printRow(Board2),
Index is Index + 5
subs(Tail, Index).
Output: subs(<Original List>, 7).
0 1 2 3 4
Can anyone give me some help on how to implement it?