I'm trying to write an update function, which can be applied to a list and then to NestList
it.
As the function has to manipulate the given variable I figured I need HoldAll
or HoldFirst
, so the variable is passed by reference.
update[x_] := (x[[1]] = x[[1]]*2; x)
Attributes[update] = HoldAll;
This works:
mylist = Table[3, {i, 1, 3}]; update[mylist]
It gives:
{6,3,3}
But now I want it to be nested in a list. The code
NestList[update, mylist, 3]
should give
{{6,3,3},{12,3,3},{24,3,3},{48,3,3}}
but it gives
Set::setraw: Cannot assign to raw object 12.
Set::setraw: Cannot assign to raw object 12.
Set::setraw: Cannot assign to raw object 12.
General::stop: Further output of Set::setraw will be suppressed during this calculation.
{{12,3,3}, {12,3,3}, {12,3,3}, {12,3,3}}
Am I right that this is happening because NestList
evaluates mylist
before applying update? If so, how can I stop this? I can't set Attributes[NestList] = HoldAll;
, right?
Any help is appreciated :)
Cheers :D