Dynamic as function argument

Mathematica provides many functions that Dynamic can handle as an argument. For example, the FileNameSetter function has the following option:

 FileNameSetter[Dynamic[name]] uses the dynamically updated current value of name, with the value of name being reset if a different file is chosen. 

It is interesting how things stand with the definition of a function template that takes a dynamic expression as an argument. For example, here is one attempt to wrap a dynamic version of a LocatorPane function:

 SinLocatorPane[Dynamic[sinvalue_]] := LocatorPane[Dynamic[x, (x = #; sinvalue = Sin[First[#]]) &], Plot[Sin[x], {x, 0, 10}]] 

What is the correct template for dynamic expression? Are there any caveats using a dynamic argument inside a function definition?

+6
source share
1 answer

If you want to write a function that updates the value of a specific variable, it is like passing a variable by reference. The standard way to achieve this in Mathematica is to use Hold* attributes for 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]} 

will work as your expected. Your code worked because Dynamic assigned HoldFirst , and this allowed your code to update the sinvalue variable. Otherwise, Dynamic is not really needed.

+4
source

Source: https://habr.com/ru/post/886169/


All Articles