0

I know side effect and non-referential transparency mean different thing. "side effect, which implies some violation of referential transparency." "Referential transparency means that an expression (such as a function call) can be replaced with its value; "

However, I wonder if there is any example of function that has no side effect but non-referential transparency If yes, would anyone give me an example (e.g. in C function)

wew tie
  • 23
  • 5

3 Answers3

2

Consider a function that interrogates the external environment, eg returns the current time, or the free space on your hard disk, etc.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
1

You are asking:

I wonder if there is any example of function that has no side effect but non-referential transparency If yes, would anyone give me an example

Here is an example:

int globalValue = 0;

 int f(int x)
 {
   globalValue++;
   return x + globalValue;
 }

 int g(int x)
 {
   return x + globalValue;
 }
// assuming the compiler orders the methods to execute from top to bottom
int p = f(1) + // f(1) == 2 , globalValue == 1 : side effect
        g(1) + // g(1) == 2 , globalValue == 1 : no side effect
        f(1) + // f(1) == 3 , globalValue == 2 : side effect
        g(1);  // g(1) == 3 , globalValue == 2 : no side effect

In this example f performs a side-effect and it is not referentially transparent, while g does not perform a side-effect, but it is non-referentially transparent as well (since the two calls of g(1) produces two different values).

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42
Renzo
  • 26,848
  • 5
  • 49
  • 61
0

Referential transparency implies no side effects: if you can replace a function with the value it returns there can be no side effects: The function can only compute a value based on the values passed to it.

The statement "side effect implies no referential transparency" is just the contrapositive of the above and logically equivalent to it.

Joni
  • 108,737
  • 14
  • 143
  • 193