Search code examples
javascriptfunctional-programmingpurely-functional

Functional Programming Purity Requirements for Hash functions


I am following this guide to begin learning functional programming w/ Javascript: https://medium.com/@cscalfani/so-you-want-to-be-a-functional-programmer-part-1-1f15e387e536#.iynj38h83

It defines a Pure function as:

  • Operate only on input parameters
  • Useful Pure functions take at least one parametre
  • Useful Pure functions must return something
  • Pure functions cannot change external variables/No side effects
  • Pure functions will always produce the same output given the same input

The following function violates the contract:

function notPure(data) {
  let ts = new Date();
  return md5(data + ts);
}

But the following would be Pure:

function pureFunction(data, ts) {
  return md5(data + ts);
  }

Assuming I understand correctly, what is the point? I'm young to this part of the field. I don't yet understand how this is useful. Does the inclusion of the time stamp inside the function make the function stateful and break purity?

What is the advantage to forcing these values to be created elsewhere and passed into a pure function as a parameter?


Solution

  • Programs will always have state. Always. The idea of pure functional programming is that you push state (insofar as is possible) to the edges of your programs: for example scan in a line of user input, do a bunch of pure functions on it, and spit the output back to the console.

    This has a lot of advantages:

    • Pure functions are easy to test
    • State-related bugs have fewer places to hide
    • Pure functions can be made to generate very performant machine code.
    • No cache invalidating. Since the functions are referentially transparent, you can memoize at will.
    • It opens the door to really cool stuff like hot code reloading. I cannot over-state how awesome that is.

    So for your example function, how would you test the impure version? With the pure version its simple, you pass it a date and assert it returns the expected output.