taylor_sin = x -> x - x^3 / 6 + x^5 / 120; test_fun = function x -> d d = abs(sin(x) - taylor_sin(x)); // bad -- taylor_sin is invisible here endsince taylor_sin is a local variable in the scope outside the body of test_fun and therefore can not be accessed inside. One solution to this is passing the value of taylor_sin to the function
test_fun = function (x, f1, f2) -> d d = abs(f1(x) - f2(x)); end test_fun(1.25, sin, taylor_sin) 0.0009258624152However, this may make the function calls more complicated. Sometimes there are certain important data values that many functions need to use and share. It would be convenient to store such a value in a public area that can be accessed inside any function. Such a variable is called a global variable.
The Shang interpreter maintains a global variable that can be accessed anywhere. The name of this global variable is global. It is a structure whose attributes can be used as if they were independent variables. For example, to create and initialize or modify a global variable named volume, one can do
global.volume = 75
To reference a global variable, the keyword and the dot global. can be omitted if the surrounding scope does not have a local variable with the same name. For example
global.taylor_sin = x -> x - x^3 / 6 + x^5 / 120; test_fun = function x -> d d = abs(sin(x) - taylor_sin(x)); /* this will be ok */ end test_fun(1.25) 0.0009258624152Note that
A global variable can have a domain which limits the values that can be assigned to the variable to a set. The domain is optionally declared when the variable is first assigned a value using the keyword in. For example, a global variable defined as follows can only take one of the three values 0, 1, or 2.
global.u = 1 in {0, 1, 2};After this, a command global.u = 3 will fail and cause an error, since 3 is not in the domain of global.u. Note that domain can only be specified once. If domain is not specified when the variable is created, it has a default domain _ALL, which is the set of everything.
oz 2009-12-22