gp doesn´t complain if one tries to change the value of an independent variable during a function evaluation, but also doesn´t do it.
f(x) = (x=x-1, x)
pr f(1)
gives 1, not zero. In hindsight it is clear why, x is not a regular variable.
This function
bin(n) = sum [i=0:31] (ex=31-i, n >= 2**ex ? (n=n-2**ex, 10**ex) : 0)
pr bin(128)
was supposed to return a "binary" representation of n, but it only gives series of ones. There are probably other, more mathematical cases where one might get the idea to modify the independent variable. The summation operator simply cries out to be used to do sth. iterative without having to resort to recursion. ;-)
I´m not sure it´s worth the effort to make this work (after all one can always assign the value to a regular variable first, using the serial evaluation operator), but I guess it should throw an error.
The x in function definition f(x) is not an "independent variable" it is a "formal parameter" (called a "dummy variable" in the gnuplot source code comments). Once you convince your brain that you cannot change the value of a formal parameter, it becomes easier to rewrite your function definition as:
I think the more serious limitation is that gnuplot currently lacks a mechanism for local variables in a function. The above rewrite works because n and ex are manipulated as global variables, but this means that their value is not preserved across function evaluation. It would be cleaner if they could be recognized or marked as local to the function even though their names shadow the names of global variables.
The reason and workaround are clear, I just thought the user should get cautioned if he tries to modify x. ;)
Of course if gnuplot had such local variables, then the dummy variables could just be treated as ones inside the function, too, right?
Perhaps additional local variables could be defined like this
, where a, b, c shadow global variables of the same name, just as x and y do already, and are reset before every evaluation.
The development version now supports local variables