I'm working on some classical data structures (stack, queue, etc.) and want to mimic oo style in MMA. As a first attempt, I want to store an array in an Association, like this:
q = <|elems -> ConstantArray[Null, 4]|>
<|elems -> {Null, Null, Null, Null}|>
Later, I want to side-effect my array, like this
q[elems][[2]] = 42;
Set::setps: q[elems] in the part assignment is not a symbol. >>
Ahh, yes, of course, I need a symbol... Next attempt is this:
q = Module[{storage = ConstantArray[Null, 4]},
<|elems -> Hold[storage]|>]
<|elems -> Hold[storage$1987]|>
In[4]:= ReleaseHold[q[elems]][[2]] = 42
During evaluation of In[4]:= Set::setps: ReleaseHold[q[elems]] in the part assignment is not a symbol. >>
42
Oh, yeah, that's not going to work.
I could do the following, but it's going to copy the array every time and defeat the purpose of implementing classical algorithms (that being "efficiency"):
q = <|elems -> ConstantArray[Null, 4]|>;
SetAttributes[setQ, HoldFirst];
setQ[q_, slot_, item_] :=
Module[{newElems = q[elems]},
newElems[[slot]] = item;
q[elems] = newElems;
q[elems]];
setQ[q, 2, 42]
{Null, 42, Null, Null}
It looks like I need some kind of variant of Part
that doesn't evaluate a held symbol on its left-hand side -- a PartHoldFirst
. I don't see a way to do this with stuff I know.
Answer
Maybe I don't understand what you're trying to do, but...
q = <|elems -> ConstantArray[Null, 4]|>
q[[1, 2]] = 42;
q
<|elems -> {Null, 42, Null, Null}|>
q[[Key[elems], 4]] = 99;
<|elems -> {Null, 42, Null, 99}|>
So whether you set by position or Key
it works.
Comments
Post a Comment