Referential Transparency is one of the corner stones of functional programming that allows us to apply equative reasoning to our code. However it does so at a cost to performance, by use of immutable objects.
Some functional programming languages like Idris solve this performance problem via the use of Uniqueness Types and Borrowed Types to allow in-place updates of objects (side effects) as long the overall net effect is as if we were still using immutable objects.
Idris lead me to think about C. When you program in C using no references at all (zero reference), then could all of the zero references could be considered to be transparent?
That is to say. If you program in C updating your all variables in place with side effects, while using just the Stack Space (no pointers, no heap), then Have you achieved Referential Transparency? And can you apply still Equational Reasoning to your code?
I'll admit that I did not think about global variables at all, and that will break RT.
Heres an example of what I've imagined:
#include <stdio.h>
struct A5 {
int x[5];
};
A5 basicSort5(A5 nums) {
int n = 5;
for (int i = 0; i < n-1; ++i) {
for (int j = i+1; j < n; ++j) {
if (nums.x[i] > nums.x[j]) {
int tmp = nums.x[i];
nums.x[i] = nums.x[j];
nums.x[j] = tmp;
}
}
}
return nums;
}
int main() {
A5 nums = {7,3,2,8,9};
A5 sortedNums = basicSort5(nums);
for (int i = 0; i < 5; ++i) {
printf("%i\n", sortedNums.x[i]);
}
return 0;
}
basicSort5
is referentially transparent (and thread safe) because it is not using references. The exact same code in Java is not referentially transparent because it forces everything to be a reference.
I should of extended this question to C++. Because I believe if you use move semantics, and code in a linearly typed style, then you keep RT while also obtaining the performance benefits of Idris's Unique Types. And if you make a mistake coding in linear typed style then you just wear the cost of a memcpy and still keep RT. I just want this theory confirmed.
I think I've made a mistake. Move semantic will only help if I'm using heap space hidden inside a class. I will always have some sort of copying going on, even if its a 4 byte pointer.