Some functions have identities, which are values that tell you where to start calculating. In this episode, we look at what identities are, some examples of them, and how you can use them in your own code.
►► Audio, Video, and Transcript available: https://lispcast.com/what-is-a-functi...
►► Subscribe on iTunes: https://itunes.apple.com/us/podcast/t...
Transcript
Is a function's identity? By the end of this episode, you'll know what an identity is and how to use them in your code. My name is Eric Normand. I help people thrive with functional programming.
This is an important topic because many common operations, operations we use every day, have identities. You might not know that term, but you've definitely used them. It's a fundamental idea from algebra, and it tells us where to start an operation.
Basically, it's the value you start with. When you're counting, you're going to start at zero. You don't start at one. Before you start counting, you're at zero, then the first thing you count down when it gets to one.
Counting is just adding one each time. Zero is the identity value of addition. Multiplication also has an identity value, it's one. If you multiply one times anything, you get that number. Same thing with adding zero. If you add zero to anything, you get the number back. That's what an identity means.
There's other identities all around. If you're adding letters to the end of a string, you're going to start with an empty string. If you're adding elements to an array, you're going to start with an empty array.
The same property holds, if you stake a string and you concatenate on an empty string to the end, you get the same string out. The same thing if you take an empty array and you concatenate them, you're going to get the original array out.
You can look at all sorts of operations and try to find if they have an identity. The ones that have an identity tend to be the more algebra feeling ones. I'm talking about hash map merge.
If you merge two hash maps, basically copying the keys and values from one into the other, the identity is the empty map. Another property of the identity is it has to work in both sides.
With addition, you can say, 10 plus 0 or 0 plus 10. The identity works in both positions. Same with hash map merge. If I have an empty hash map and I merge on a non-empty hash map, I get that non-empty hash map out. If I reverse the direction, and I start with a non-empty hash map and I merge in an empty hash map, I get the non-empty hash map out.
Another way to look at identities is that they are the empty value. That's the empty array, the empty hash map, zero empty string. Whatever kinds of data structures you're looking at, there's going to be some empty version of it.
Информация по комментариям в разработке