DEV Community

Discussion on: Should Pure Functions Be Self-contained

Collapse
 
vonheikemen profile image
Heiker

In the first snippet i would say that thisWontBePure is pure. As far as i know pureFunction is a constant. What could possibly change the value returned by pureFunction at runtime?

Consider this:

function add(a) {
  return function inner(b) {
    return a + b;
  };
}
Enter fullscreen mode Exit fullscreen mode

I would say that inner is still a pure function because the value of a can't change once is locked in the closure.

If a function doesn't have side effects and mantains referential transparency, to me that is a pure function.

Collapse
 
geolamp profile image
George Lampadaridis • Edited

mmm you got me thinking. What if :

var c = 0;
var obj1 = {
        valueOf: function () {
            c++;
            return 1;
        }
    };
var obj2 = {
        valueOf: function () {
            c++
            return 2;
        }
    };
function add(a) {
  return function inner(b) {
    return a + b;
  };
}
console.log(add(obj1)(obj2));
console.log(c);
Collapse
 
geolamp profile image
George Lampadaridis

I messed up the code format. Used from stack overflow... Sorry for asking this here, how can I format code in a comment?

Thread Thread
 
vonheikemen profile image
Heiker • Edited

The syntax highlight can be activated with a block closed in triple backticks, and optionaly a language name. Like this:

```javascript
console.log('hello');
// some code
```

Thread Thread
 
geolamp profile image
George Lampadaridis

Thank you sir. Sorry for the irrelevant question again.

Collapse
 
vonheikemen profile image
Heiker • Edited

Fair question. This is javascript, right? In a dynamic language you can only write code in a functional style and hope that no one does a trick like the one you did there.

In your example inner becomes impure because valueOf is impure (it changes some state outside of its scope). So if an impure function gets executed inside of a "pure" function than it is no longer pure.

Collapse
 
xania profile image
Ibrahim ben Salah

obj1.valueOf is not referential transparent!

Collapse
 
xania profile image
Ibrahim ben Salah

not all side effects are the same, only observed side effects are relevant for the definition of pure function.