2
$\begingroup$

I want to use function as a placeholder for a bunch of codes while making the function also produce an output

Consider

A={0,0,0};
f[x_]:=Block[{},A[[x]]=1;A]
f[1]

this will make A to be {1,0,0} while outputting A. (The Block[] is necessary. I don't know why, but it isn't my main question). My main question is how to make the following code work

f[A1_] := Block[{}, A1[[1]] = 1; A1]
A={0,0,0};
f[A]

I want this changes A to {1,0,0} while outputting it. How can i make this work? Are there alternatives for placeholder of codes? If my question shows an obvious lack on knowledge on some area, such as how defining function works, some reference would be helpful.

$\endgroup$
1

1 Answer 1

6
$\begingroup$

Give f the Attribute HoldFirst:

ClearAll[f]
f[A1_] := (A1[[1]] = 1; A1)

SetAttributes[f, HoldFirst]

A = {0, 0, 0};
f[A]

{1, 0, 0}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.