Agreed... I know out of memory is my usual stop condition. Usually, its because i forgot to do the increment or some other mind-numbngly simple thing. Or even having my break condition setup, but never break out of the recursion.
Recursion is used a lot in game development, scenegraphs or other tree-related data structures, sorting algorithms, pathfinding, etc. Anything that requires iterations, layers, or nesting likely uses recursion.
Tbh a lot of the hardest things I’ve see are 9/10 in game development. It kinda sucks that the industry is just a mess cause it’s also imo the coolest swe out there next to embedded aerospace/automotive.
mhmm.. not really. only academically. most recursion algorithms can be written with normal loops. recursion is harder to reason about, allowing mistakes to recurse indefinitely, and can blow the call stack either way. Only a few languages have tail call optimizations to allow infinite recursion.
Depends on the true structure. I once had a graph to search in, which was mostly tree-like but not completely. I first tried recursive, but ended up doing it iterative to de-dublicate nodes, that had already been visited through another branch.
I mean: The implementation was definitely more messy, but the behavior was cleaner.
Yeah, that irked me. It just sounds like whatever they're doing doesn't require it and they simply don't have use cases for it. They don't need it, so they extrapolated that nothing needs it.
I'm not about to agree with the "only academically", but one advantage iteration does have over recursion (which the comment you're responding to suggests) is that it's typically easier to modify the procedure to add functionality or account for edge-cases. Sometimes this comes with large initial overhead in building the explicit stack for the iterative problem though, and if your problem is simple and doesn't expect extension, recursion can be easier to work with.
Just gonna have to agree to disagree on the "only academically" thing. I've built my own ECS (entity component system) game framework with an integrated scenegraph that is built on recursive logic to manage, query, and do all sorts of things with the entities. I've used recursion enough personally and professionally that I don't find it confusing to use or debug anymore. It took a while at first, but it's very intuitive now.
It also depends on what you're doing with the data. If you're just trying to drill down into something to find a value and your location (so to speak) doesn't matter, then a loop and a couple variables for maintaining references might be fine. But if every recursive call is dependent on values passed along or can affect other calls on the stack, then recursion might be the best solution vs a very over-engineered one just to avoid using it. Recursion is a tool though, so it isn't the best solution for everything.
It comes up a lot when you start to work with things like, e.g., C++ variadic templates. It's pretty common to parse a parameter pack recursively, by designing the function to consume the first one or two args and call itself again with the rest, and end on a specialisation or compile-time branch when the pack is empty. (The compiler will usually then inline this into the desired actual function. Essentially breaking it down into easy-to-swallow steps, then putting the bricks together.)
It's very often useful. Writing e.g. a DFS with a loop is possible (and indeed sometimes necessary to avoid stack size limits) but really annoying. And graph or tree structures come up a lot.
I'm not in academics and I've had to do it multiple times. One example is a control flow graph. An example of a recursive data structure that's really hard to handle without recursion is an abstract syntax tree.
There are graph libraries I guess but that's a lot of effort to use one, and it doesn't really help with ASTs
I work in automotive and there are multiple functions per core with "shared" stack, so using more stack is not waste of RAM, as long as you use less than others. 'RAM usage' is considered private memory like globals. Recursion is forbidden because it is hard to analyse (proof that it always stops within stack memory limit). Recursion is just syntactic sugar - everything can be done with loops and buffers.
I accidentally backed into recursion years ago building Minesweeper in Excel to get that cool “cascading”effect when multiple empty spaces are connected. It wasn’t until after the project concluded and I was Googling related concepts that I came across the name. Made me feel pretty smart a small while.
Well, declaring the argument of the function pointer is quite ugly yeah, but actually using the function later is quite simple and clean. And if you know you'll need that same type of function pointer argument, you can just make a typedef and the writing of the arguments will be quite clean
Well, that's the first case I mentioned, where you're only worried about it a single time, otherwise you can make it as a typedef and then that will be a clean way to write it afterwards. Having it be ugly one single time in the codebase isn't that big of a deal imo
and you can't really make closures without resorting to horrible tricks, if the higher level function doesn't allow passing a generic void* argument or something.
There's a gcc extension for closures but afaik it requires the stack to be executable, which sounds horrifying
I was quite surprised the other day when I learned that both Haskell (the language) and currying (the mathematical transform) got their names from a guy named Haskell Curry.
Function that takes a function as an argument and returns a function as a result. The function is then a lambda that has a captured context that contains a reference to a particular instance of a class.
Finding my first use case for making a Python decorator function made me feel like a wizard too. 12 years later I had to Google what’s it called again…
I’m going to self report here…. I hate functions as arguments. It’s a major hit to readability in my eyes. Granted any engineer with some experience can read it and understand it, I always feel it takes more time understanding the nuance of it and why it is optimal to have it as an argument.
The only time I regularly do this is for web server handlers.
Best way to understand the usefulness is to look at a comparison algorithm, and think about how you would phrase it to an employee.
"See these two piles here? I want you to go through them both from top to bottom. From each pair, keep one and throw the other out. Put them in a new pile, upside-down, then flip the entire pile right-side up when you're done."
"Okay, how do I know which one to keep?"
"Hmm... whichever one has the fanciest cursive writing on the front."
Now, think about what that should look like in programming terms.
We want a function that can take two arrays (piles), and compare them from front to back (top to bottom).
We want to make a new array (new pile), that contains one element from each pair (keep one).
The original arrays have the same ordering, and the new array should use the same ordering as they do. [Making the new pile in opposite order, then flipping/inverting its order, was meant to model this.]
We want to be able to choose how we compare the arrays, instead of being locked into a specific comparison all the time.
Logically, this tells us that we want to have a function that takes two arrays and a comparator as parameters. The comparator can be a simple tag, with each tag corresponding to a type of comparison, but that limits us to only using built-in comparisons; whenever a new comparison is desired, we need to update the system and recompile the entire thing.
// Pseudocode.
Array array_compare(Array l, Array r, ComparaTag tor) {
const int sz = min(l.size(), r.size());
Array result(size = sz);
for (int i = 0; i < sz; i++) {
switch (tor) {
// Comparison logic here.
// Will be a big blob of ugliness.
// Could be hoisted out of the loop, but that means using a function pointer.
// (So it's a no-go, right?)
// Compare l[i] to r[i], put chosen value in result.
result[i] = WhicheverCompareWeSwitchTo(l[i], r[i]);
};
}
return result;
}
If we allow the caller to pass a comparison function, however, then the algorithm is forwards-compatible with any possible comparison, and also becomes much easier to write... and at the same time, significantly cleaner.
// Pseudocode.
Array array_compare(Array l, Array r, ComparaFunc tor) {
const int sz = min(l.size(), r.size());
Array result(size = sz);
for (int i = 0; i < sz; i++) {
result[i] = tor(l[i], r[i]);
}
return result;
}
Making the comparison algorithm take a comparison function as an argument is thus preferred. (Most comparison algorithms default to "less than" if no comparison is supplied, for reference.)
More generally, this is useful for the "apply" pattern, where you take a function and a pile of parameters, and then call that function on each parameter in turn.
// Actual C++ example.
template<typename Func, typename... Ts>
void apply(Func&& f, Ts&&... ts) {
( f(std::forward<Ts>(ts)), ... );
}
It lets you take a mechanism that's meant to apply to one item, and expand it over an entire sequence, essentially. It comes up often with sequences in many languages, and is a crucial tool for Excel-like databases, among other places.
Like, say, you want to change an entire sentence to upper-case, but your toupper() only works on individual characters. You could loop over the entire string yourself, or you could use an apply-style function to do it for you.
std::string str = "This string is quite the test case, let's see that upper limit.";
std::transform(str.begin(), str.end(), str.begin(), toupper);
Ultimately, it's just "do x task with y tool", but that is extremely handy to have!
Yeah I mainly write in Go and have a lot of juniors on the team. I tend to focus on readability a focus so anyone can pop in and understand what is happening easier. But I get the benefits of it. Just not my favorite
I don't know Go, so I just Googled how lambda functions (function literals?) work in Go out of curiosity, and yeah, their syntax is kinda clunky... I'd avoid using it too
C# lambdas have a very clean syntax in comparison and more often than not makes the code more readable
I wrote a pokemon-esque battle engine once that was functionally pure, abdolutely zero internal state. This was so I could recreate the same battles during testing and possibly as a validation or replay tool.
This meant I had to pass a random number generator in as a parameter, which was kind of amazing because I could replace it with the identity function during development and testing to check for math errors (each call gave a default value that the teal rng discarded).
I understand you don't like them, but I assure you when used correctly, they are absolute powerhouses, and often make things easier than any alternative.
C++ has only had lambdas since 2011. Before, functions as arguments were possible but really annoying, such that it was often easier to inline an algorithm than to attempt to use a generic version needing a function object. But these days yeah callbacks are quite common.
Yes that's a big limitation. I'm also not sure how it's "less verbose". If you happen to already have a function with the right prototype and functionality, then sure. Also captureless lambdas can be converted to function pointers.
The compiler can produce more efficient code if the exact type and captured variables of a lambda are known at compile time. Also, a lambda can reference the caller's local variables.
It's not so much state as context. If your callback can only access global variables it's a problem. Typically there's a void * you can pass along for that purpose, but it's annoying to set up.
Most of my C++ development was in an embedded environment with lots of C libraries, so lambdas were typically not an option. The simplicity of function pointers also just grew on me, feels much more intuitive to just slap a * in there instead of defining templates
C++20 added concepts and operator<=> which are pretty decent steps forward. Nothing groundbreaking apart from that I would say, many incremental improvements though, notably to constexpr. Modules and coroutines could be cool if they worked well. There's reflection now too. But of course no contracts.
Concepts was a good addition in my opinion and I use them semi regularly. I had no idea operator<=> was added and that tripped me out till I looked it up lol.
I'm finally going to be able to use <=> at work and I'm looking forward to it. Writing comparators is annoying, and easy to do wrong. Recently I added a comparator related assert and found 3 separate incorrect comparators.
Before node had promises the way you'd handle async code is by passing a callback function into whatever you were doing. Can you imagine the level of nesting?
What's really cool though is not a function that takes another function as an argument, but a function that returns another function.
template<typename Func, typename... Ts, typename R = std::invoke_result_t<Func&&, Ts&&...>>
R call(Func&& f, Ts&&... args) {
return f(std::forward<Ts>(args)...);
}
int call(int (*f)(int, int, int), int a, int b, int c) {
return f(a, b, c);
}
I mean.... Yes... But it's really no different that defining a function elsewhere and then calling it before you call the function that takes it as an argument. In fact, functions as arguments are harder to read and harder to understand the intent.
I'd rather define a bunch of helpfully named static helper methods separately. Readable code is better code
Edit: unless Claude is the one doing the reading. Then go off, I guess. Claude LOVES functions as args
Man I remember when I made a hideous function of type function that received a function and returned a function as a result (different function), I think I'm missing something in there but it was all function so the rest down, I don't remember exactly why, only that it was a hacky way to get around passing a function across 4 classes or something similar, that couldn't share inheritance for some reason, and I remember that it was funny having a function of type function blah blah blah that was a brainfuck to understand and my colleagues could not make heads or tails out of it and could not find a better way to achieve the desired result, I was told to never make something similar, it was used nevertheless xd
im making a game where you can play either against bots or people and made a generic game_vs_bot function that takes another function to run the bot (and before i added that i was copying the logic of displaying state and making moves for each bot)
If you're new to programming, this teaches you a few things
- functions are just places to jump to in memory locations - methods are syntactic sugar that accepts the pointer of the <thing> in <thing>.<method> as the first argument - static and dynamic dispatch when using generics like this instead of the `dyn` keyword
No, but when you put async, await, non allocs and miri passing through - thats a problem, whatever those idiots posts there is not going to work in any real case scenarion
Aren't higher order functions everywhere in rust? I haven't done a lot with the language, but I seem to remember that the standard library had the usual suspects, like functors and *such.
Returning one requires you to wrap it in a smart pointer. Manage lifetimes if you're brave enough. Figuring things like returning &mut FnOnce(...) is fun.
7
u/cheezballs 9d ago
You're gonna love JavaScript.
303
u/LowB0b 9d ago
you would love lambda-calculus
751
u/Tomlambro 9d ago
A function which calls itself… recursively
95
u/fbpw131 9d ago
and returns another function.
202
u/gaurav_the_piggy 9d ago
Come to C and see the power of function pointers!
88
u/TheIvoryAssassinPub 9d ago
What are you talking about? It’s just Tuesday
25
u/Professional_Top8485 9d ago
Giving .net function as parameter to dll function and making state machine
23
u/Hola-World 9d ago
I’ll have some curry please.
21
u/Positive_Method3022 9d ago
High order functions are definitely great
38
u/Due-Consequence9579 9d ago
Function that takes a function as an argument and returns a function as a result. The function is then a lambda that has a captured context that contains a reference to a particular instance of a class.
12
u/MrJake2137 9d ago
And calling it a higher order function
12
u/AWzdShouldKnowBetta 9d ago
Generics 🤤
11
u/sebjapon 9d ago
Finding my first use case for making a Python decorator function made me feel like a wizard too. 12 years later I had to Google what’s it called again…
11
u/NatoBoram 9d ago
Making a filter function that takes a function as an argument and that's passed to a filter function 👌
8
u/just-bair 9d ago
Functional bros
8
u/ILikeLenexa 9d ago
Wow, this is a callback.
43
u/Scrub_DM 9d ago
I’m going to self report here…. I hate functions as arguments. It’s a major hit to readability in my eyes. Granted any engineer with some experience can read it and understand it, I always feel it takes more time understanding the nuance of it and why it is optimal to have it as an argument.
The only time I regularly do this is for web server handlers.
11
u/ZunoJ 9d ago
Lol, if that is enough, you can feel like god with some more learning little one
3
u/mad_scientist_kyouma 8d ago
A function that takes a class as an argument 🚬
3
u/CranberryDistinct941 9d ago
I only really know Python. Are key functions not common in other languages?
1
u/cwjinc 9d ago
I can still remember the first time my C code passed a pointer to a function to a function and it was decades ago.
1
u/__sean_eng__ 9d ago
we are bringing back factories and manufacturing . MPGA
1
u/stupled 9d ago
So much abstraction!🤤
1
u/technic_bot 9d ago
Oh i did that once
Still smile when i see it on the codebase nowadays
1
u/Undernown 9d ago
I recently combined lambda's with a composite pattern, allowing to create tree of functions.
1
u/Shimshi1998 9d ago
Try making a cache decorator, that shit feels so good when it works
1
u/silently--here 9d ago
A decorator?
1
u/FoxedDev 9d ago
I just talked about the Java implementation of this with a friend for 2 hours.
1
u/Buyer_North 9d ago
wait until you learn about cpp concepts...i love it so much. You can use it like the definition of composition...
1
u/conundorum 9d ago
Pick your Cthulhu?
1
u/Outrageous_Umpire_77 9d ago
Maybe a bit wrong context but c# delegates go brrrr
1
u/jamesxtreme 9d ago
Even better if it returns a function.
1
u/ItsOmniss 9d ago
Very useful to select, delete and sort
1
u/EmergencyArachnid734 8d ago
Oh no haskell not again
1
u/gene66 8d ago
For me is reflection, when I finally figure that out it felt like 5 head to me.
1
u/Headstroke 8d ago
I miss handwriting code, doing lambdas made me fell smart
1
u/gravel_consumer420 8d ago
Maybe you are
1
u/mountaingator91 8d ago
I mean.... Yes... But it's really no different that defining a function elsewhere and then calling it before you call the function that takes it as an argument. In fact, functions as arguments are harder to read and harder to understand the intent.
I'd rather define a bunch of helpfully named static helper methods separately. Readable code is better code
Edit: unless Claude is the one doing the reading. Then go off, I guess. Claude LOVES functions as args
1
u/xzinik 7d ago
Man I remember when I made a hideous function of type function that received a function and returned a function as a result (different function), I think I'm missing something in there but it was all function so the rest down, I don't remember exactly why, only that it was a hacky way to get around passing a function across 4 classes or something similar, that couldn't share inheritance for some reason, and I remember that it was funny having a function of type function blah blah blah that was a brainfuck to understand and my colleagues could not make heads or tails out of it and could not find a better way to achieve the desired result, I was told to never make something similar, it was used nevertheless xd
1
u/Ratstail91 7d ago
I've made a scripting language (cough https://toylang.com/ cough) and one of the pillars of its designs are first class functions and closure support.
Because slips on sunglasses I can't finction without it.
1
u/jolharg 7d ago
currying is so basic
1
u/DTCreeperMCL6 3d ago
It used to make me feel smart but now it feels a little dumb when I do it. Theres almost always a better way to do it.
-12
u/markiel55 9d ago
That's a code smell in my book.
-4
u/Background_Issue_144 9d ago
Don't do it, its almost always a bad idea and what you want to do can be done in a simpler way
-22
u/Zhuzha24 9d ago
now try it in Rust with real case scenario and data
-4
u/JackNotOLantern 9d ago
No, i hate it. You do that only if you can't define it normally.
0
u/[deleted] 9d ago
[deleted] — view deleted comment