r/learnprogramming • u/Temporary-Warthog250 • Apr 05 '22
Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them
Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.
Someone else who reads yours and does understand it, try to explain it to them to help them learn
1.6k
Upvotes
11
u/plastikmissile Apr 05 '22 edited Apr 06 '22
You know what functions are, right? That's what lambdas are essentially. They are functions. They have a weird syntax, but in the end of the day they are nothing more complicated than functions. But here's the kicker, many languages these days have taken a page from functional languages and are now treating functions the same way they treat data. Those functions are packaged as lambdas. So you know how functions can take numbers and strings as inputs and outputs? Well now they can take lambdas as inputs and outputs as well.
Let's see how that looks like. I'll be using C#, but the concept is the same everywhere. Let's say we have a class that has an internal value. I'd like to have a method that does operations on that internal value with a value that I provide. The old way of doing it would be something like:
Looks good. It works. But say, I decided I wanted to add subtraction and division as well. Then some annoying customer wanted to add something even more complex that involves more than one operation. In the old way, we would have to keep adding different methods.
Now let's see how we might tackle this the functional way:
So now we have a new method that we called
Mathand it has an argument of typeFunc<int,int,int>. That basically means it expects that argument to be a function that takes twointvalues and outputs anintin return. This one method will replace the 'Add' and 'Multiply' methods from the old solution, as well as any others we can think of (as long as they just take two values with the first one being the internal value). And here is how use it:See how powerful that is?