3
$\begingroup$

I have long code that I would like to divide in several parts (for readability) to be saved in different files. Then, later, I could use those parts into a different notebook. The parts I am thinking of are not functions per se but only part of the code. I have tried something like this:

Manipulate[ Get["Manipulate\\Main.txt"]; Plot[b[f],{f,fmin,fmax}], Get["Manipulate\\Controls.txt"] ] 

Is this possible at all?

$\endgroup$
2
  • 5
    $\begingroup$ Certainly. Turn your code into functions, save them in packages, and delineate which parts are private implementation details vs. public functions you want to expose. Importing fragments of code that are not functions or nicely contained units you can reason about will likely to lead to things leaking everywhere and make debugging harder. $\endgroup$ Commented Jun 29, 2020 at 17:50
  • $\begingroup$ I think it might be a little trickier because Manipulate moves in mysterious ways. $\endgroup$ Commented Jun 29, 2020 at 21:41

1 Answer 1

3
$\begingroup$

One way is as follows. It is important that the code is inserted into Manipulate[] without being evaluated. Note the use of Hold and OwnValues.

In a file, say "/tmp/body.wl" or better yet, https://pastebin.com/raw/TbzQYHqz:

body = Hold[ b = Sin[aa*n #] &; Plot[b[f], {f, fmin, fmax}] ]; 

In another file, say "/tmp/controls.wl" or better yet, https://pastebin.com/raw/0bt8a6x7:

controls = Hold[ {fmin, 0, 1}, {fmax, 2, 3}, {n, 1, 5, 1} ]; 

Then

Clear[body, controls]; fmin = -1; (* to show global definitions do not affect the result *) b = 0; (* ditto, but this is overwritten when /tmp/body.wl is read in *) aa = 2; (* a global variable used in body *) << "https://pastebin.com/raw/TbzQYHqz"; (* read in body *) << "https://pastebin.com/raw/0bt8a6x7"; (* read in controls *) Hold[ body, controls] /. OwnValues@body /. OwnValues@controls // Flatten // Apply[Manipulate] 

enter image description here

If you want something more complicated as shown in your example, then things get more intricate, depending on how much variation you want to be able to handle. For instance, moving Plot[..] out of the definition of body:

body = Hold[ b = Sin[aa*n #] & ]; Hold[ body, Plot[b[f], {f, fmin, fmax}], controls] /. OwnValues@body /. OwnValues@controls /. Hold[Hold[b1_], b2_, Hold[c___]] :> Manipulate[b1; b2, c] 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.