user1161552
user1161552

Reputation: 91

Mathematica not evaluating #1

I defined 2 objects:

f=x^2
g=x->#1

Why does this:

f /. x -> #1 &[5]

give me the expected result:

25

But this:

f /. g &[5]

gives me:

#1^2

As if the #1 wasn't evaluated to 5. Please help.

Upvotes: 3

Views: 4676

Answers (3)

lineage
lineage

Reputation: 895

Replace g=x->#1 with g=x->#1 & and f /. g &[5] with f/. g[5]

Upvotes: 0

Chris Degnen
Chris Degnen

Reputation: 8680

You can make it work by keeping the pure function components together.

f = x^2
g = x -> #1 &

f/. g[5]

25

To run it over a list form the function before mapping.

f = x^2
g = x -> #1
list = {1, 2, 3, 4, 5};
b = Block[{a}, Function[f /. a] /. a -> g]
Map[b, list]

{1, 4, 9, 16, 25}

And for the specific problem in the comments...

vars = {x, y};
f = x + y;
g = Table[vars[[i]] -> Slot[i], {i, 1, Length[vars]}];
b = Block[{a}, Function[f /. a] /. a -> g];
list = {{1, 2}, {3, 4}, {5, 6}};
Map[b[Sequence @@ #] &, list]

{3, 7, 11}

With Mr. Wizard's answer this can become:

vars = {x, y};
f = x + y;
g = Table[vars[[i]] -> Slot[i], {i, 1, Length[vars]}];
list = {{1, 2}, {3, 4}, {5, 6}};
Map[Evaluate[f /. g] &[Sequence @@ #] &, list]

{3, 7, 11}

Upvotes: 2

Mr.Wizard
Mr.Wizard

Reputation: 24336

Function (short form &) has attribute HoldAll:

Attributes[Function]
{HoldAll, Protected}

Therefore g remains unevaluated. You can force it with Evaluate:

Evaluate[f /. g] &[5]
25

Evaluate will not work deeper in the expression; you cannot write f /. Evaluate[g] &

Upvotes: 2

Related Questions