r/Clojure • • Sep 21 '16

What is really a pure function?

http://staltz.com/is-your-javascript-function-actually-pure.html
3 Upvotes

5 comments sorted by

5

u/Bolitho Sep 22 '16

Why does the author consider throwing an exception as impure? As long as it is always the same (like it would be with the call to sum ()), it is still pure, isn't it?

3

u/halgari Sep 22 '16

Most functions programmers (even Haskell'ers) would consider pure aren't infact pure. For example, is this a pure function?

(defn adder [x]
  (fn [y]
    (+ x y))

The inner function is, but the outer is not. Not only does it return a new instance of a function on every invoke, but the creation of a closure requires calling the memory allocator which itself is a side-effecting function that can throw an exception (out of memory errors).

So in essence really nothing that is in the slightest way useful is pure.

2

u/CurtainDog Sep 23 '16

Well yes and no. Anything that is computed (such as the inner function in your example above) is not pure as it takes time and energy to produce a result. What we're more interested in is if a function can be observed to be impure. If we can't tell the difference between a new and old instance of a function then it doesn't matter if a new instance is created each time.

2

u/grav Sep 21 '16

I think something like this would brake the "safe" sum function:

Array.isArray.toString = function(){return "function() { [native code] }"}

I guess any invocation from inside the sum function can produce a side effect.

2

u/sveri Sep 22 '16

I already commented the pure function discussion on the klipse blog: http://blog.klipse.tech/javascript/2016/09/21/valueOf-js.html

Wikipedia clearly says: "The function always evaluates the same result value given the same argument value(s)."

What the author does is to change the value of the inputs, but in an "uncommon" way, I don't know any other word for it. Still, no matter how I change the values of the arguments, as long as I change them, my function will return different values, according to their input values. But it still is pure, because it does exactly what it says.

Following the logic of the author, there will never be a pure function in a finite state machine, because somehow I can always make it return different values by exploiting the limitedness of our machines.