10
$\begingroup$

It is easy to create a list of indexed variables

F/@{1,3,6,8}

I would like to assign values in the same line of code

F/@{1,3,6,8}={2,4,6,0}

but it complains Set::write: Tag Map in F/@{1,3,6,8} is Protected. Why, whats going on?

$\endgroup$
0

5 Answers 5

2
$\begingroup$
index = {1, 3, 6, 8};

values = {2, 4, 6, 0};

Create an Association

data = <|Rule @@@ Transpose[{index, values}]|>

<|1 -> 2, 3 -> 4, 6 -> 6, 8 -> 0|>

Define a Lookup-function

F[i_] := Lookup[data, i, {}]

The 3rd parameter of Lookup replaces missing keys

F[-1]

{}

F[1]

2

F[{1, 3, -1}]

{2, 4, {}}

$\endgroup$
11
$\begingroup$
Evaluate[F /@ {1, 3, 6, 8}] = {2, 4, 6, 0}
$\endgroup$
1
  • 5
    $\begingroup$ @PhillipDukes - As shown, since Set has the attribute HoldFirst, you must Evaluate the LHS $\endgroup$
    – Bob Hanlon
    Commented Nov 10, 2023 at 22:01
10
$\begingroup$

another method:

F = AssociationThread[{1, 3, 6, 8} -> {2, 4, 6, 0}]
F[1]

2

$\endgroup$
5
$\begingroup$
Clear[F]
MapThread[Set,{F /@ {1, 3, 6, 8}, {2, 4, 6, 0}}];
F /@ {1, 3, 6, 8}

(* {2,4,6,0} *)
$\endgroup$
4
$\begingroup$

Just another way:

Clear@F;
Set @@ {F /@ {1, 3, 6, 8}, {2, 4, 6, 0}};

DownValues@F
(*{HoldPattern[F[1]] :> 2, HoldPattern[F[3]] :> 4, HoldPattern[F[6]] :> 6, HoldPattern[F[8]] :> 0}*)

F /@ {1, 3, 6, 8}
(*{2, 4, 6, 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.