Transcript from the "Associativity" Lesson

[00:00:00]

>> Kyle Simpson: Quick note on composition, this is a mathematical concept, but there is a concept called associativity. Associativity is a mathematical concept. If I said one plus two plus three, the plus operator is associative and that means that the way that I group these, if I did one plus two and then did plus three, I'd end up with six.

[00:00:24] If I did two plus three first and then added one, I'd also end up with six. So whatever order that I group them in, it doesn't matter, I get the same result, right? That's a characteristic of math, of certain math operations, is that they are associative. Well, the reason we bring this up is because composition is also associative.

[00:00:46] Which means, if I have a list of functions that need to be composed, I can compose them in any grouping. And I'm gonna still get the same end result. So here I have a composed two utility. This one can only handle two at a time. It doesn't handle three or 20, it just handles two, okay?

[00:01:04] So if I grouped minus two and triple together and then composed that composition with increment, we get the same thing as if I compose triple and increment and then compose that with minus two, so let me show you that code. So I am going to say compose two of minus and triple, minus 2 and triple, that's line 12.

[00:01:25] That composition is composed with increment. So we still have the same right to left ordering, we're still gonna do increment, triple minus two. The ordering is still gonna be increment triple and minus two. That's what f is a composition of. Then I have p here, which does compose two with triple and increment.

[00:01:45] And then that is composed with minus. Still the same order, increment, triple, and minus two. The f and the p functions look different, but they have the same result because composition is associative. That's actually super useful to us, because it means that we can actually do currying and partial application on our compositions.

[00:02:10] You don't have to know all the functions that are going to participate in a composition all up front. You could curry the compose utility and provide two or three of them now, and then take that result and compose it with something else later, and take that result and compose it with something else later.

[00:02:28] And what are you doing? You're creating a more specialized function every time. Because we're using currying to make a more specialized function. So the associativity property of composition sounds sort of a nuance but it's actually really critical to making composition so useful.