mostly-adequate-guide icon indicating copy to clipboard operation
mostly-adequate-guide copied to clipboard

Ch3: transforming impure functions to pure

Open mattfysh opened this issue 7 years ago • 4 comments

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?

mattfysh avatar Sep 08 '16 20:09 mattfysh

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)

safareli avatar Sep 08 '16 20:09 safareli

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)()

mattfysh avatar Sep 08 '16 21:09 mattfysh

@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"

jmilkiewicz avatar Feb 28 '17 07:02 jmilkiewicz

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

F1LT3R avatar Mar 03 '18 16:03 F1LT3R