Message Boards Message Boards

0
|
4081 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Is there something like forward declarations?

Posted 4 years ago

A notebook normally consists of a sequence of function declarations and (main-)code that calls those functions. Some functions may depend on others. E.g:

f[x_]:=2*x;
g[y_]:=f[y]^2;
Print[g[4]]

64

In this case, everything works fine since no code uses other code that has not been defined before.

But if we use another sequence, this notebook (or block of code respectively) cannot be executed properly since g is undefined at the time of execution:

f[x_] := 2*x;
Print[g[4]];
g[y_] := f[y]^2;

g[4]

If you have a larger notebook with many functions depending on others, this problem cannot be resolved. You have to execute the notebook once with many errors so that all function declarations are executed. Up from then, everything is fine.

Is there some mechanism in WL like "forward declaration"? I. e. in the second piece of code something like "Uses[g]" before "Print[g[4]]" which will execute the declaration of g before executing "Print ..."

For packages, there is "Needs" which is a similar mechanism.

POSTED BY: Werner Geiger
2 Replies
Posted 4 years ago

You could put your function declarations in Initialization Cells

POSTED BY: Hans Milton
Posted 4 years ago

That's right. How stupid of me! In fact, I use initialization cells all the time, but only for the actual setup code. Of course, I can use them for everything that is used elsewhere.

POSTED BY: Werner Geiger
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract