Message Boards Message Boards

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

What is the benefit of using formal variables?

I am working on four-point parabolas with the function FourPointParabolas on the Function Repository, and I noticed that the function uses formal variables. For example, I can enter formal x displayed as an X with a dot underneath it with escape period x escape, which is the character's alias. I wonder what the benefit of using a formal variable is aside from its protection. I understand this is a benefit to prevent conflicts with y, and you can use formal y. I'm not familiar with formal variables and have read the documentation at tutorial/MathematicalAndOtherNotation#173509264 under the Formal Symbols section.

For example, if I created a function similar to FourPointParabolas, would it be a good idea to use formal variables instead of any variables?

POSTED BY: Peter Burbery
2 Replies

Peter,

here is a more trivial example:

ifunc[\[FormalX]_] = Integrate[\[FormalX]^n Sin[\[FormalX]^2], \[FormalX]]

In such a case the use of formal parameters makes sense, because you want the rhs being evaluated once and for all (therefore "=" is used, and not ":="), but then you have to make sure that X does not get replaced by something else. Of course you can do a Clear[x] immediately before (if possible), but IMHO formal parameters are more elegant.

POSTED BY: Henrik Schachner
Posted 1 year ago

The pertinent characteristic of a symbol like \[FormalX] is that it has the attribute Protected (by default). A protected symbol cannot be given new definitions (you might have noticed code that protects important symbols after giving them some definitions). So, if you're creating a package intended for others to use, it's a fairly safe assumption that you won't get name conflicts if you use formal symbols. It's not guaranteed, of course. Additionally, formal symbols come with no default definition, so if you just want to use something as a literal indeterminate type of symbol, a formal symbol is a good choice--you get no name conflicts and it will display as itself.

Now, let's say you're building a package and you have some symbols/variables that are being used as parameters or package-specific constants or just have some usage internal to your package. In that case you don't care about the display aspect, but you still want to avoid naming conflicts. In such a case you'd probably use the Context mechanism. You might have a variable like MyPackage'Private'MyFancyParameter.

[NOTE: The single quotes used in that variable name are used because backtick is a formatting syntax on this site. In Mathematica code you'd use backticks.]

POSTED BY: Eric Rimbey
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