Does any programming language use variables as they’re in maths

mathprogramming-languagesvariables

In maths, a variable means you can put any number there, and an equation will still be true:

root(square(x)) = abs(x)

In programming languages, this is not so: a var can change. In Python:

y = (x**2)**.5
x *= 2
assert y == abs(x)

will raise an exception, since x in the last line is not the same.

Are there programming languages that use immutable variables?

Best Answer

To answer your title question "Does any programming language use variables as they're in maths?": C, C#, Java, C++, and any other C style language use variables in the way they are used in math.

You just need to use == instead of =.

If I take your original

root(square(x)) = abs(x)

Then I can translate that into C# directly without any changes other than for the syntax. Math.Sqrt(Math.Pow(x,2)) == Math.Abs(x)

This will evaluate to true for any value of x as long as x squared is less than the max for the data type you are using. (Java will be grossly similar, but I believe the Math namespace is a bit different)

This next bit will fail to compile in C# because the compiler is smart enough to know I can't assign the return of one operation to another operation.

Math.Sqrt(Math.Pow(x,2)) = Math.Abs(x)

Immutability has nothing to do with this. You still need to assign the value in an immutable language and it's entirely possible that a given language may chose to do this by using = as the operator.

Further proving the point, this loop will run until you exhaust legal values of x and get an overflow exception:

 while (Math.Sqrt(Math.Pow(x, 2)) == Math.Abs(x))
        {
            ++x;
            System.Console.WriteLine(x);
        }

This is why mathematicians hate the use of = for assignment. It confuses them. I think this has led you to confuse yourself. Take your example

y = (x**2)**.5
x *= 2
assert y == abs(x)

When I turn this into algebra, I get this:

abs(2x) = root(x^2)

Which of course is not true for values other than 0. Immutability only saves you from the error of changing the value of x when you add extra steps between evaluating the Left Hand Side and Right Hand Side of the original equation. It's doesn't actually change how you evaluate the expression.

Related Topic