Wackscope Variables
What are Wackscope Variables? #
Wackscope variables are best described using an example:
In this example, is a wackscope variable. They've been named "wackscopes" because they defy normal scoping rules one would expect in a regular programming language— they look like they are part of the global scope and act like it too: The wackscope complains that the variables it uses— and — aren't defined.
Despite this, works without issue when used in the function , because defines both and for it. This might seem super counterintuitive for people already familiar with programming. However, think of it like you're directly substituting in for .
In general, a "wackscope" variable is any such variable that fits the following criteria:
- The wackscope uses other variables that aren't in the global scope.
- The wackscope is used in another context that defines variables (e.g. function parameters, list comprehensions, sums) which have the same name as the ones the wackscope uses that aren't defined in the global scope.
Why use Wackscope Variables? #
When you write a complex function in Desmos, you will often want to use the same "sub-expression" twice. Consider the example below:
Notice how is repeated three times throughout this function. We can fix this by moving to a dedicated wackscope variable and replacing all instances of with . This might seem a bit silly for a function this small, but keep in mind that you can write much larger functions in Desmos which will benefit much more from wackscopes. Here is what you will have with a wackscope applied:
As you can see, this example is a lot simpler. It's also a lot more performant— in the example above, is calculated three times. In the example below, is calculated once and assigned to , which is then reused without recalculating it.[citation needed] So not only did adding a wackscope make this function simpler— it also made it run faster.