I interpret this question as asking how define a function that works like the built-in functions Part
, AppendTo
, and PrependTo
; i.e., a function that performs non-standard argument evaluation because it has been given one of the attributes from the Hold
family of attributes.
Normally, in what is referred to as standard evaluation, all the actual arguments passed to a function are evaluated before the function sees them. For a function to able to modify the binding of a global variable it must see that variable's identifier unevaluated. Mathematica provides a mechanism for achieving this with what it calls attributes. For more about standard evaluation, nonstandard evaluation, and attributes mean, you should read the collection of articles found here.
Now I will present an example showing nonstandard evaluation applied to a situation like the one you describe, which involves a module. I have picked a somewhat more elaborate example than Mr.Wizard did in order to illustrate more of the issues that come up when dealing with nonstandard evaluation.
SetAttributes[procrustes, HoldAll];
procrustes[victum_, size_] :=
Module[{v = victum, n = size},
If[! (Head[n] === Integer && n > 0), Return[$Failed]];
If[Head[v] =!= List || v === {}, Return[$Failed]];
Unevaluated[victum] = If[Length[v] >= size, v[[;; n]], PadRight[v, n, v]];]
Some unit tests
Block[{v = {a, b, c}}, (procrustes[v, #]; v) & /@ {5, 3, 3, 1}]
{{a, b, c, a, b}, {a, b, c}, {a, b, c}, {a}}
Block[{a = 42, b = Pi, c = {}}, procrustes[#, 1] & /@ {a, b, c, 0}]
{$Failed, $Failed, $Failed, $Failed}
Block[{v = {1}, a = 42., b = Pi, c = {}}, procrustes[v, #] & /@ {a, b, c, 0}]
{$Failed, $Failed, $Failed, $Failed}
When defining a function that uses standard evaluation, I make heavy use of argument patterns to validate actual arguments. When defining a function with nonstandard evaluation, I forego that luxury and fall back on procedural argument validation as I have shown here, the reason being that the argument patterns needed become at best awkward in the nonstandard case.
AppendTo
ori++
:) $\endgroup$Module
is getting in the way of your idea without seeing exactly what you've coded. Please post a minimal working example. $\endgroup$