Mathematica provides many functions which are capable of handling Dynamic
as an argument.
For example, the function FileNameSetter has the following variant:
FileNameSetter[Dynamic[name]]
uses the dynamically updated current value of name, with the
value of name being reset if a different file is chosen.
I wonder how one goes about defining a function pattern that takes a dynamic expression as an argument. For example, here is one attempt to wrap the dynamic variant of the function LocatorPane:
SinLocatorPane[Dynamic[sinvalue_]] :=
LocatorPane[Dynamic[x, (x = #; sinvalue = Sin[First[#]]) &],
Plot[Sin[x], {x, 0, 10}]]
What is the correct pattern to use for a dynamic expression argument? Are there any caveats with using the dynamic argument inside the function definition?
If you would like to write a function that updates the value of a certain variable, this is like passing a variable by reference. Standard way of achieving this in Mathematica is to use Hold*
attributes on your function.
SetAttributes[SinLocatorPane, HoldFirst];
SinLocatorPane[sinvalue_] :=
LocatorPane[Dynamic[x, (x = #; sinvalue = Sin[First[#]]) &],
Plot[Sin[x], {x, 0, 10}]]
Then
{Dynamic[sv], SinLocatorPane[sv]}
would work as your expected. Your code worked because Dynamic has HoldFirst
attributed and this allowed your code to update variable sinvalue
. Otherwise Dynamic was not really needed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With