4
$\begingroup$

I have come across a simple example of bizarre behaviour, i.e.:

Function[t, t*c] /. c -> 0

which outputs

Function[t, t 0]

How can I make the product "t 0" evaluate to 0?

$\endgroup$

2 Answers 2

7
$\begingroup$

Function has the attribute HoldAll:

Attributes[Function]

{HoldAll, Protected}

This explains the behavior you're seeing. There are many ways to handle this. One that I like is to use Inactivate/Activate:

expr = Function[t, t*c] /. c -> 0;

Activate @ Inactivate[Evaluate @ expr, Function]

Function[t, 0]

With Inactivate, you can control which parts of expr get inactivated, i.e., you can do partial evaluations. As a silly example, suppose you have:

expr = Function[t, 0/0 + 1 + 2]

Function[t, 0/0 + 1 + 2]

You can avoid evaluating 0/0 as follows:

Activate @ Inactivate[Evaluate @ expr, Function | Times | Power]

Function[t, 3 + 0/0]

$\endgroup$
5
$\begingroup$

While Carl Woll's answer is probably better in general, here I would just use the more terse MapAt :

expr = Function[t, t*c] /. c -> 0;

MapAt[ Evaluate, expr, 2 ]
Function[t, 0]

Note that the operator form makes this particularly convenient to use:

Function[t, t*c] /. c -> 0 // MapAt[Evaluate, 2]
Function[t, 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.