MostlyAdequate / mostly-adequate-guide

Mostly adequate guide to FP (in javascript)
Other
23.42k stars 1.87k forks source link

Ch3: transforming impure functions to pure #305

Open mattfysh opened 8 years ago

mattfysh commented 8 years ago

Something to note is that you can transform some impure functions into pure ones by delaying evaluation:

var pureHttpCall = memoize(function(url, params) {
  return function() {
    return $.getJSON(url, params);
  };
});

I'm having a hard time seeing where a transformation from impure to pure is occurring, possibly given the "before" code is missing. Just to be clear, in this example: const callWithParams = pureHttpCall('http://...', {a: 1, b: 2}), the pure function is pureHttpCall, compared with callWithParams which is impure?

safareli commented 8 years ago

key is delaying evaluation. pureHttpCall always returns same function and calling pureHttpCall has no side effects. you can memoize it's results. you could also do something like this:

var run = function(o) {
  return o.action(...o.args);
}
var pureHttpCall = memoize(function(url, params) {
  return {
    action: $.getJSON,
    args: [url, params];
  };
});
run(pureHttpCall(...))

So here pureHttpCall is pure. first example is just easiest one (just wrap in function)

mattfysh commented 8 years ago

thanks @safareli - that makes sense! I'm just wondering what was "impure" before it was transformed to "pure"? The function calling $.getJSON is clearly impure due to the side effect (run in your example), but I'm not sure if "transform" is the right word to use here:

...you can transform some impure functions into pure ones by delaying evaluation

Are we transforming a function here? Rather, it appears we're wrapping it with memoize and partial application to create a new function (i.e. not transforming an existing one). This is made apparent when you see the difference in signature:

impureHttpCall(url, params) versus pureHttpCall(url, params)()

jmilkiewicz commented 7 years ago

@mattfysh Right, "transforming" is a bad word in this context. Simply the idea is that if you have a function that is impure you can still "transform" it (by wrapping it- you do not need to use memoization or partial application ) to be pure by simple wrapping it. This new "pure" function will "fit" in your pure machinery, but you are right at some point (in impure layer of your application) you would have to finally "run it"

F1LT3R commented 6 years ago

Chapter 3, great chapter. Thanks for the inspiring work. 👍