- Podcasts
- ADSP: Algorithms + Data Structures = Programs
- Episode 36: std::transform vs std::for_each
Episode 36: std::transform vs std::for_each
ADSP: Algorithms + Data Structures = Programs
- July 30, 2021
- 36 min
About this episodeIn this episode, Conor and Bryce talk about std::for_each vs std::transform, a ton of algorithms and a little bit of APL. Date Recorded…
In this episode, Conor and Bryce talk about std::for_each vs std::transform, a ton of algorithms and a little bit of APL.
Date Recorded: 2021-06-30
Date Released: 2021-07-30
- Bryce’s Live C++ Coding
- Conor’s Live APL Coding and an example
- C++ std::for_each
- C++ std::transform
- C++20 std::ranges::transform
- C++20 std::views::transform
- C++ range-based for loop
- C++ Seasoning by Sean Parent
- C++ std::replace
- C++ std::replace_copy
- C++ std::mismatch
- C++ Algorithm Hierarchy Tweet
- C++ Algorithm Hierarchy Lightning Talk
- C++ std::adjacent_difference
- C++ std::sort
- The Pursuit of Elegance by Matthew May
- C++ std::partial_sort_copy
- APL ⊢ (same or pass or identity)
- APL ÷ (divide)
- APL ⌊ (min or lesser of)
- APL / (reduce)
- APL forks
- Fantasy birds - S’ Combinator
Intro Song Info
Miss You by Sarah Jansen https://soundcloud.com/sarahjansenmusic
Creative Commons — Attribution 3.0 Unported — CC BY 3.0
Free Download / Stream: http://bit.ly/l-miss-you
Music promoted by Audio Library https://youtu.be/iYYxnasvfx8
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
Episode 36: std::transform vs std::for_each
I honestly don't think I've ever coded a std4 each in production. And I mean, yeah, I like std4each is like in my opinion, I think Jake Hemstad, he's a a co-worker that works on Rapids at NVIDIA. He says that like basically like we both agree, but he has some great quip that I'm I'm gonna I'm gonna fail to get uh correct. But it's basically that like a std4 each like isn't an algorithm. Um like it's yeah, the only the only time when it's useful is if you're calling the parallel version, but yeah, I've s I've seen that, but also too, I just like uh a lot of times where there's a std for each, I think that there's like another algorithm that's more like better named that you just uh oh interesting.
So I was writing an example the other day um where I was um uh so essentially it was an example where I would go and find the min element in a vector, and then um in a sec second pass, I would go and divide all the elements of the vector by the minimum element. So essentially it was um uh like scaling everything to the minimum element. So after the second pass, the um the minimum element in the vector would then be one. This is assuming that the vector was numeric of a numeric type. So after the second pass where you divide everything by the min element, the min element would be one and everything else would be, you know, um uh uh uh that its original value divided by the min element. So it would be normalization. Yeah, normalization. Well, not not really not not uh normalization in the sense of like math normalization, because that would be that would be the value divided by the unit the the unit norm, which is a different thing. But it's sort of like um uh a scale. I don't know, actually. I'd have to go remind myself how math works. But I don't think it's I don't think it's normalization in the in the math sense, because I think normalization in the in the math sense would would normalize everything to be a value from between zero and one, I believe. Um uh but yeah, it's it's sort of like it's what you do if you want to take a series of um like time measurements and uh convert them to speed up relative to the slowest. Um and so then I I was like asking myself, well, how do I write that second loop in the most C way? And the first thing I was gonna do was a std range is for each, but this was for slide code, so I'm like, that's a long identifier. I and like then I gotta put a lambda in there too. Maybe this will just be clearer as a range-based for loop. And uh so what would you use for that second pass?
Yeah, yeah, but but but okay, so so if if we're using ranges, I've already started off, I've got to std ranges transform. That's like that's already as verbose as like the the for loop and the parens uh uh for the range-based for loop. And then on top of that, I gotta stick a lambda in there. And the lambda has to capture, because it has to capture that min element. I think that code is way clearer as a range-based for loop, not as a transform.
So so okay, let's let's look at the for each here. The for each takes one input range, right? The vector, and it modifies in place. The transform, I I want to modify these elements in place. So I gotta give it the input range, which is in this case it's just gonna be the vector v. But then I also have to give it an output iterator. Not an output range, but just an output iterator, right?
So so the code, the the the for each line, uh the lambda is the same in both cases. No, it's not the same in both cases. And the in the transform case, in the in the for each case, the lambda takes the element by reference and it does um like divide equals to it. And it does it in place. In the transform case, we we still need to capture, but we'll take the the element by value and we'll return e divided by uh min. But the the big the big flaw that I see in using the transform here is that I have to pass the input twice. I have to pass V once as the input range, and then I have to do V DOP again. Oh, that is just like no, like this is the use case for 4H. Like I I reject your and Jake's argument that there's no use case for 4H. Like in-place modification of a thing, that's what 4 H is for. But but that's not even the one that I'm arguing for. The one that I'm arguing for is this this little beauty, which is gonna be a whole lot nicer.
Which there's no lambda, it's just 4 auto ref E colon V E divided by equals min. And it's like half the characters. It is it's 27 characters, the transform one is a 71 character line, the for each one is a 54 character line. And even if you are using like uh even if you take out the namespace qualification, um, the std ranges namespace qualification, the for each line is still 41 characters. The transform line is still 58 characters. Now there's there's no way that that anything other than the range-based for loop is the correct option here. But anyways, why don't why don't you show me the why don't you show me how you do this in APL?
I mean, I definitely would not use a non-range-based for loop for that. And actually, let let's let's look at what that would look like. Um let's look at what that would look like. And the reason I wouldn't use it is like I just are like I just think it's like more herb. Well, you know what, I I I take it back. Uh the if I'm doing something index-based, I might do that. And like, yeah, I know that we're not supposed to, but in some cases, if you're doing something index-based, it might be, you know, the way to go. Alright, alright. So we're looking at uh um we won't we won't do a uh a classic for loop with iterators because that would just be that would just be rough. And we won't do like the correct thing of doing like std vector, you know, size type. We'll just assume it's gonna be size t because secret, it always is size t. Or you like we could just use int here, that'd be fine. Size ti or equal zero. I mean, maybe I should use int here because that'll be a few fewer characters, and that is how people would uh how people would write it. Um so like even even this one is like shorter than the than the for H1. And of course, it's not all about size. I mean the reason the reason to not use this one, uh uh the the index-based for loop one, of course, is that it's index based, so you know it's very easy to make a mistake here and to end up going out of bounds. Um and actually when now that I've finished writing the line, it is actually like like one character longer, exactly one character longer than the uh stood ranges for each one.
And and that's what I think I said at the beginning is that the reason to use the 4H, the algorithm, is, you know, if you want to parallelize it, you know, then the the different going from the range-based for loop to a parallel for loop in C requires completely rewriting it. Going from a stdd for each to a parallel stdd4h is adding one argument. Going from a uh uh a transform to a parallel transform is adding one argument.
No, because like with trans, like that's literally the purpose for for each existing. No. Uh this is actually a great argument for us to have right now, or a great debate for us to have right now, because the next topic we're gonna talk about is gonna be the parallel scan um algorithm. And in the downstream of the parallel scan algorithm, we have exactly this problem. And uh, and I believe I use in my examples a for each.
So I yeah, I I think that like uh for each is for like side effecty things. And that is not what a transform is for. A transform is for applying a unary operation to some range of values. And you can do stuff that like, you know, side by side, these look similar, but like fundamentally a transform doesn't need to have side effects.
Uh he um this this is a new hire on uh on my team. Uh uh he is his name is spelled um like George but with two eyes at the end. Um but he is told uh he's um uh he's he's Russian. He he lives in Moscow. Um he's told us that he um prefers to go by George, at least among English speakers. So that's what we've been that's how we've been been saying it. So I I I do not speak Russian. I do not know I'm actually not even sure. I I I do not know how to do it. No, no, no. No, I I'm not sure. I'm not sure whether I'm not sure the origin of his name. Um but but he likes to be called George.
Alright, so uh George, Jake and I had this meeting. All the details don't matter, but um we were talking about naming at one point, and the observation was made that certain algorithms have underscore copy versions, and then certain algorithms do not. Um and like finding the what what's the like delineating factor that causes that? Because like arguably um replace and replace copy, or not arguably, replace is just a specialization of transform. You can like in in the I've uh a couple times on Twitter I've like posted little diagrams of uh like algorithm hierarchies where uh like mismatch is the most general version of a bunch of other algorithms um like adjacent find, etc. Um and transform is also at the root of a hierarchy. And uh there's only a couple that are specializations, but replaces one of them. And so we have replace and replace copy, but we don't have transform and transform copy.
Um or in the the case that we were specifically talking about with uh with George and Jake, adjacent difference and adjacent difference copy. Correct. And so an example of an example of the dichotomy here is we have sort and uh and then we have sort copy, is that right? Uh we don't have sort copy, but um we do have like partition and partition copy, but that's the thing is those or or or so I guess the dichotomy here is we have sort, which is the um uh sort is the un uh uh the unannotated name. It doesn't have like you know a sort in place or anything on it. And so sort is in place, whereas transform is not in place.
And so one could argue that the the naming style of the algorithms is inconsistent. That correct we should have said, okay, all of the in-place algorithms will have a suffix, or all of the non-in-place algorithms will have a suffix. We should have picked one kind to have the good names. And by good names I mean names that don't have a prefix or suffix. Um and so like in that world, you would either have sort, um, like in place, like the current thing currently called sort would be called, you know, sort in place. Um and and uh then you would have a sort that takes both an input and an output, and then you'd have a um, you know, and then transform would be as it is today. Or the alternative would be you would sort would be as it is today, where it takes one range and it does the sorting in place, then you'd also have a sort copy. Um, and then you'd have uh like transform would be different from what it is today, it would be an in-place transform. And the thing that we call transform today, we would instead call transform copy. Um in either of those two worlds would be consistent, um uh, but that's not the world we live in.
So what uh what's interesting is that I like I haven't gone through and checked every single one, but uh for the copy algorithms, underscore copy that has that uh suffix, I'm almost certain actually that's not true what I was about to say. Uh but a lot of them are permuting algorithms. Like sort, sort, um, for instance. I was about to say that, but then I just realized replace copy is is a counterexample because replace is not doing a permutation. So like partition and sort, uh it makes it makes sense for those the defaults of those to not have a third iterator with like an output where you're doing some copy. The most common case I would assert is that you're sorting that range. You don't need to do like you don't need a second or third iterator to define your um your output. And arguably, like just having said that out loud, it's kind of makes sense why you would do the same thing for replace, because replace almost always you're gonna be doing that in place. Whereas it's not as it's not as obvious that for the more general version of transform that you always want to do that in place. Um but I think that's a mistake.
Um well and and but but that is the reason behind that is the rationale behind the the design. And if you look at the standard itself, and if you look at how it's organized, there's um a distinction between, you know, what's considered the modifying sequence operations, the non-modifying sequence operations, the partitioning and the sorting operations, like the when you look at the way that they're organized in the standard and the way that they're grouped together, it makes a little bit more sense. And you know, we've been talking about consistency because I think both you and I um have a great desire for consistency across APIs, but the the design of the algorithms today picked a design that was not consistent across all the algorithms, but the reason for that was to be consistent with with what the use cases were going to be. That, oh, the most common case for sorting is we're sorting this thing in place. So therefore, the thing called std sort should be the one that does that. Um, but for you know, for transform, the in place is I I assume I think was assumed at the time that it was thought that that was not the most common case. Um and so therefore the transform the thing called std transform should not be the in-place one. Um and so there there is a logic there. It's not just like that it was random. There was a thinking that you know, certain algorithms of permutation type algorithms, you'll typically do those in place, whereas other algorithms um you'll often not do them in place. Um and you know, I think one of the one of the interesting things that you and I share in common, Connor, and one of the one of I think the things that makes your you know perspective and analysis of um uh our algorithms library unique is looking at things with a bird's eye view. Um like ta or or another way to think of it is like taking a step back. Like one of the things that you do that you're really good at is like you take a step back and you don't look at locally like what's the right uh decision for this one algorithm. Like you you take a step back and you look at How do all of these different algorithms fit together? And like, you know, how do how do they form a collective set of operations? And like what series of combinations, what combination of different um uh uh operational semantics are missing? You know, those tables from your algorithm intuition talk. That's the sort of thing that I mean. But like you and I both look at the C standard algorithms, and we sort of like take a step back and we look at the trends and patterns across all of the algorithms. And I think that's why we see this inconsistency and it um and it bothers us. I as I as I always frequently joke, um uh it's Bryce's law. I would I would rather be uh consistently wrong than inconsistent.
Yeah. Yeah, it's uh this makes me think of a think of a couple things, but yeah, now that now this is now the second time in like uh a week that I've been thinking about this underscore copy thing, and it makes me want transform and transform copy. Because also, too, a part of the reason you don't like the transform and you prefer the fore each is because of that iterator. And if we had the transform version that was just in place, you would you would be less averse to using, in my opinion, what what is the correct algorithm.
Um and that transform in place has an interesting and notable difference from for each, which is that for each, as I said before, the way that the for each version of this algorithm worked was you took the input argument by reference and inside of and in the lambda. You took it by you took the argument by reference, and um the the parameter, the element by reference, and you would modify it within that lambda. So it was it was less functional, right? That that I'm taking this this this argument by reference, I'm modifying it. Whereas in an in-place transform, I would take it by value and I would return it. And I would return a new thing. And that is, you know, more pure and more functional.
Yeah. And this this sort of, you know, you say the word consistency. I I really like the word uh and prefer symmetry. Um there's a book that uh is called The Pursuit of Elegance, I believe. And um it's a fantastic book. I'll make sure I got the title right. If not, I'll come back and fix this in post. But I'm pretty sure it's the pursuit of elegance, and it talks a lot about symmetry and why um we find symmetric things beautiful. Um there's a whole chapter section on Jackson Pollucks, who's a famous artist, um, who basically like all his paintings are just like flicking paint. So it's these like crazy sort of just like uh amalgamation of different paint colors, and you know, it looks sort of like a child could do it, but they've studied these paintings and they have like fractal properties that like the people have tried to duplicate with like you know, ladders and they've tried all these different techniques, and like people can't figure out how Jackson Pollack uh does it. And uh in fractals, like there's a certain sense of symmetry because you zoom in and zoom out, and it's always the same ratio of uh you know pieces of the fractal that you're looking at. Anyways, yeah, I I love some symmetry, and this brings me to the second point that I was um gonna mention earlier about Kate Gregory has talked about how um like partial sort copy is a terribly named algorithm, and we should call it you know uh top N or something like that. But there is a part of me that actually really likes the name partial sort copy because it's symmetric with its sibling algorithms. There's a partial sort, there's a sort, the underscore copy is is a you know, as Jonathan Bacara calls it, a ruin, um, but just like it's a common prefix or suffix, uh in this case it's a suffix. And I really like the symmetry of the the names. And that's something that we've like taken into consideration with the C23 range algorithms that we're adding in adapters, where we're trying to be consistent. Um when we were adding algorithms that look at adjacent elements, we you know, we we are trying to choose the prefix that's common. So like I personally don't uh necessarily prefer adjacent, but because adjacent find and adjacent difference like exist already in the C standard library, that's the prefix that we went with. Anyway, so yeah, symmetry, symmetry I think is super important. And yeah, when it comes to like renaming things to I'm I'm not sure how you feel about top end versus partial sort copy, but it's it's uh I I I I'm actually torn on like should like yes, top N is what you would reach for, but a part of me thinks that like you know, what does Sean Parent say is that you know like engineering is a profession and it's something that needs to be studied in like our our libraries and the standards. Um like he advocates that everyone, every C developer should read through the standard, which I'm not necessarily saying I agree with, but I think the sentiment that you know our libraries and our tools like they deserve time and study. And and yeah, so I I I actually don't have my mind made up on top end versus Yeah, I I don't I don't know.
I I don't love either of the names, if we're being honest. Don't don't read the C standard if you're uh if you're a user. You don't you don't need to do that. Um you know w while while while symmetry, you know, we do find symmetry beautiful. Um, you know, asymmetry can can be elegant too. I had one of my uh old friends from when I was at LSU, uh Zach, um uh he was really into uh uh biking. Um uh and uh bikes are inherently uh uh asymmetric because um you have the gear set on one side of the bike, right? Um uh and so he um he drove a Hyundai velocitor um and uh he described it as like the ideal car for him. And I was once asked him why, and he said, well, um it's asymmetrical like bikes, because it the Hyundai Velocitor is it's this like uh compact car, um uh and it's a hatchback, and it's got only three doors. So on the passenger side, there's two doors, um, but on the driver's side, there's not a door behind the driver's side. So the car, so it's it's like even now, cars are of course a bit asymmetric because the driver's side is you know on one side of the car, but they're usually pretty symmetric. But like this is a more asymmetric car than most. And like that's what sold them on the car. Was like, this is asymmetric, like bikes, and I really like bikes, and I think that there's some beauty in asymmetry.
When you think when you think about cars in general, though, they are from like to look at it from the outside, are completely symmetric. Like, and that's what that's what a lot of the times yeah, I I think I think there's been studies done that like uh objectively beautiful people have very symmetric faces. Yeah. Um it's just something, something about pattern recognition of our eyes that are just like, oh, that's easy to digest because it's it's exactly the same on both sides, and so it's it's easier for the brain to process. I don't know if I just made all that up, but um sounds right.
And and uh and and because the because I caught the visual cube at Connor didn't, when Connor said objectively beautiful, he put it in quotes, uh, presumably to suggest that he meant that what a study considers objectively beautiful or what society considers objectively beautiful is not necessarily what is actually beautiful.
Um it's interesting. I I just realized um humans have similar have that same property of of cars where humans look very symmetrical from the outside, but internally we're quite asymmetrical, right? Our brains are asymmetrical, like our you know, organs are asymmetrical for the most part, you know, hearts on one side, etc. Um So yeah, so sort of like how you know a car externally looks pretty pretty symmetrical, but like internally there's a driver's side, etc. Um Yeah, it's sort of interesting.
Oh, I I thought I saw that. But I thought it was just like random characters. The question is, can I find out where the chat is? I saw you Oh, I found it. I found the chat. I found the chat. No, that's not code. I thought it was a smiley face, Connor. I thought that was a smiley face, not APL code. So so walk me through it. Walk me through it.
I think your hair looks good long. I like it like this. There was there was a length before this current length that I did not approve of. And I I think it was mostly the length uh before the current length plus the mustache I did not approve of. But your current hair, I like your current hair.
I think your personality shines through, Bryce. Uh uh I don't know if mine does though. Yep, back to APL. So um this basically on the right here, this is your min reduction. So the slash is a reduce, and the min glyph makes it a minimum. And then um the right tack is just identity, so it just gives you back what you have. And then the the whole expression is a fork. So what happens is it applies the unary operation, aka identity and minimum to the list first, and then it takes the results of those two things and uh provides those as arguments to the binary divide function. The ordering confuses me a little bit because Yeah, this is this is infix, and then the unary operations are technically like prefix.
But yeah, in APL um unary operations are prefix and binary operations are infix, which honestly is something I don't really ever say much um because you just sort of read it and it works. Uh but when when it comes to forks, I guess yeah, that might need a tiny bit of explanation. AKA S prime combinators.
This is pretty elegant. Like it is pretty, you know, nice. Like, like, I guess what's not what's elegant it's not that I find the code elegant because I don't understand, I think, enough about APL to, you know, fully grok this. Um, but the elegant thing is the fact that you, somebody who understood APL, were able to code this up and in four characters, you know, express this problem that like you didn't you didn't know that I was gonna suggest this problem ahead of time. This is not something that like you select that we selected as you know something that you you knew was easy to express in EPL. But just like the fact that off off the cuff you were able to express this in, you know, in four characters, two operations, um uh I think speaks a lot to the power of APL. Um I mean also speaks a lot to Connor as a programmer, but um it is pretty impressive.
A fork is uh the name that Ken Iverson has given um what is known as the S prime combinator from combinatory logic, but it is it's basically just like a function manipulation. So you're whenever you have the pattern where you need to do two unary operations uh on the same input, and then take the results of those and feed them to a binary operation, that's a fork. And so like average, you sum the list and you take the length of the list, both of those are unary operations, and then you divide those two numbers. That's a fork. Take uh figuring out if something is a palindrome. Uh if you reverse it and then take identity and then just check if those things are equal, that's a fork. Like forks are everywhere.
