14 ms·
Hmm... One way that I find easier to understand partial application is to imagine that it's an object. All of the bound variables are like instance variables i
by mikekchar 9y ago
Hmm... One way that I find easier to understand partial application is to imagine that it's an object. All of the bound variables are like instance variables in the object.
Imagine that you have a collection of items that you want to map over. Unfortunately the function you want to run takes 2 parameters instead of one. What if that function was really an object with one instance variable and a method that took 1 variable. So something like this (if it formats correctly):
class Person {
constructor(name) { this.name = name; }
is(adj) { console.log(this.name + ' is ' + adj); }
};
const mike = new Person('Mike');
['smart', 'handsome'].forEach((adj) => mike.is(adj));
I think most people from an object oriented background will find this easy to understand. Instead of making an object, though, we can just make a function that binds the value in conceptually the same way:
const is = name => adj => {
console.log(name + " is " + adj);
}
const mikeIs = is('Mike');
['smart', 'handsome'].forEach(mikeIs);
Note: I don't have to make a lambda in the second case because I don't have to trip over `this` pointers, but I could if I wanted:
['smart', 'handsome'].forEach((adj) => mikeIs(adj));
Now, imagine that you have a bunch of curried functions, whose first argument is "name". Let's say "is", "jumps", "eats". You could write a function like this:
const Person = (name) => {
return { is: is(name), jumps: jumps(name), eats: eats(name) };
};
This is literally a class (minus the crazy `this` pointers).
This is one of the reasons, I really like Javascript. :-)
- agumonkey 9y agoOne major difference though, objects with multiple fields will require some sophisticated logic to ensure correct order of initialization (depending on the way constructors and setters are done). A partial function enforces some order. You can accumulate safely information and get closer to a usable and valid final piece of logic. It's less easy when you need choice although one can use subfunctions . In OOP you may have fluent interfaces, builder things but it's.. once again a lot for not much more.