How to define a variable updating function? [duplicate]

This question already has an answer here:

What are the most common pitfalls awaiting new users?

32 answers

I tried to program a Sudoku solver when I suddenly ran into this problem:

I need a function which effectivley does this:


Quasi an updater. But the code above won’t work because the only thing I get is:

SetDelayed::setps: “{{Null,Null,8,1,7,6,Null,2,Null},{Null,4,Null,Null,Null,9,7,Null,Null},{Null,Null,Null,Null,Null,Null,Null,Null,Null},{Null,7,1,8,Null,Null,Null,Null,Null},{Null,Null,Null,Null,Null,Null,6,7,9},{Null,Null,Null,5,9,7,Null,8,1},{Null,Null,Null,Null,2,Null,Null,Null,Null},{Null,5,9,Null,Null,Null,Null,1,Null},{Null,1,4,6,5,Null,3,Null,Null}} in the part assignment is not a symbol.”

The list in the error message is what I used as Sudoku in my Updater function.



2 Answers


This should solve your problem:

SetAttributes[Updater, HoldAll]
Updater[a_, b_, c_, Sudoku_] := Sudoku[[a, b]] = c

Sudoku =
{{Null, Null, 8, 1, 7, 6, Null, 2, Null}, {Null, 4, Null, Null, Null, 9, 7, Null, Null}};

Updater[1, 1, 99, Sudoku];


{{99, Null, 8, 1, 7, 6, Null, 2, Null}, {Null, 4, Null, Null, Null, 9,
7, Null, Null}}



Wow – that’s it! Thanks. Would you care to elaborate on how that works?
– TetstName123
Aug 7 ’14 at 16:29



You should download Leonid Shifrin’s book at and read Chapter 4.9
– eldo
Aug 7 ’14 at 16:54

I prefer to do it this way:

SetAttributes[updater, HoldFirst];
updater[sudoku_, a_, b_, c_] := (sudoku[[a, b]] = c);

HoldFirst keeps the variable sudoku in an unevaluated form, which means it stays a variable symbol and does not become a variable value, in your specific case a list of values. a, b, c are evaluated, because only the first argument has attribute “HoldFirst”

In the recommendations of Mma, they point out that users should write their symbols lowercase. Although this is only a convention, it is good programming practice to follow this advice. Or do you know for example that you can’t use Beta as a variable