Dear list,
I need a small program doing the following:
If L is a list of (natural) numbers the program should return a list
of lists where successively each member of L is increased by 1.
For instance (if the name of the program is DistributePlus1)
DistributePlus1([3, 5, 7, 13])
should give the result
[ [4, 5, 7, 13], [3, 6, 7, 13], [3, 5, 8, 13], [3, 5, 7, 14] ]
I tried to do it with the following program:
DistributePlus1(L) :=
block([L1 : [], L2 : L],
for i : 1 thru length(L) do
(L2 : L,
L2[i] : L2[i]+1,
L1 : append(L1, [L2]) ),
L1 );
But the above mentioned call DistributePlus1([3, 5, 7, 13]) results in:
[[4,6,8,14], [4,6,8,14], [4,6,8,14], [4,6,8,14]]
Now I am at a loss if I don't see the forest for the trees even in
this small program or if there is a problem with indexing/subscripting
and re-assigning the elements of a list.
And if there is a more elegant solution I'll be happy to learn about it.
But independently thereof I am interested in learning why the above
given program doesn't work (see also the P.S. remark).
Thank you,
Jochen
P.S.: For the purpose of debugging, I tried the same program
interspersed with some print-commands.
DistributePlus1(L) :=
block([L1 : [], L2 : L],
for i : 1 thru length(L) do
(L2 : L,
print(L, L2, L2[i], L2[i]+1),
L2[i] : L2[i]+1,
print(L, L2),
L1 : append(L1, [L2]),
print(L, L1, L2) ),
L1 );
The call DistributePlus1([3, 5, 7, 17]) now results in the following:
[3,5,7,17] [3,5,7,17] 3 4
[4,5,7,17] [4,5,7,17]
[4,5,7,17] [[4,5,7,17]] [4,5,7,17]
[4,5,7,17] [4,5,7,17] 5 6
[4,6,7,17] [4,6,7,17]
[4,6,7,17] [[4,6,7,17],[4,6,7,17]] [4,6,7,17]
[4,6,7,17] [4,6,7,17] 7 8
[4,6,8,17] [4,6,8,17]
[4,6,8,17] [[4,6,8,17],[4,6,8,17],[4,6,8,17]] [4,6,8,17]
[4,6,8,17] [4,6,8,17] 17 18
[4,6,8,18] [4,6,8,18]
[4,6,8,18] [[4,6,8,18],[4,6,8,18],[4,6,8,18],[4,6,8,18]] [4,6,8,18]
(%o25) [[4,6,8,18],[4,6,8,18],[4,6,8,18],[4,6,8,18]]
showing that by running the program the input list L is changed.
How can this be?