3
$\begingroup$

It's very helpfull to use antiderivative of a given function in the form Derivative[-1][fun][t]!

Here my example with a simple piecewise function:

fun = Which[0 <= t <= 1, Min[1, 2 (# (1 - #))/(1/2)^2], True, 0] &
Plot[fun[t], {t, 0, 1}]

enter image description here

The antiderivative evaluates as expected

Plot[(Derivative[-1][Function[t, fun[t]]][t]), {t, 0, 1}, Evaluated -> True]

enter image description here

But if I try calculate the antiderivative inside a subroutine I get strange results:

test =.
test[fu_] :=Plot[(-Derivative[-1][Function[t, fu]][t]), {t, 0, 1},
                 Evaluated -> True] 
test[fun[t]]

enter image description here

My question: What might be the reason for the obviously wrong result? Is there a simple workaround?

Thanks

$\endgroup$

1 Answer 1

4
$\begingroup$

Echo will help you see what has happened:

test[fu_] := 
 Plot[(-Derivative[-1][Function[t, fu] // Echo][t]), {t, 0, 1}, Evaluated -> True]
test[fun[t]]

enter image description here

This behavior is discussed in the document:

Modularity and the Naming of Things ▸ Variables in Pure Functions and Rules

We also have a number of related posts in this site, for example:

Unexpected variable renaming depending on form of a pure function

Is anonymous pure function a scoping construct?

Is the renaming mechanism of `With` flawed?

Enforcing correct variable bindings and avoiding renamings for conflicting variables in nested scoping constructs

There should be more.

A simple way to avoid the renaming is, using Apply (@@) to break the pure function:

test[fu_] := 
 Plot[(-Derivative[-1][Function @@ {t, fu}][t]), {t, 0, 1}, Evaluated -> True]
$\endgroup$
3
  • 1
    $\begingroup$ Clever idea to use Echo, have to remember it. Thanks for your answer! Still I don't understand why Plot-function evaluates without problems. $\endgroup$ Nov 9, 2022 at 12:38
  • $\begingroup$ @UlrichNeumann Are you asking why Plot still gives a plot in last case? If so, it's because Function[t$,…] is still a function. (Simpler example: Derivative[-1][Function[aaa, t^2]]. ) If you're asking why the renaming doesn't happen in 2nd case, it's because in that case you haven't defined the function test. The renaming is triggered by the nesting of := and Function. See the table Scoping constructs in the Wolfram Language in the linked tutorial. As mentioned therein: "When you mix these constructs in any way, the Wolfram Language does appropriate renamings to avoid conflicts." $\endgroup$
    – xzczd
    Nov 9, 2022 at 12:49
  • $\begingroup$ @xzcy Thank You very very much! $\endgroup$ Nov 9, 2022 at 15:58

Your Answer

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

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