22 ms·
I like to explain recursion by describing how I often write functions. I'll get to a bit where there's something complicated needed, like a loop with a lot of
by chris_st 6y ago
I like to explain recursion by describing how I often write functions. I'll get to a bit where there's something complicated needed, like a loop with a lot of conditional logic. So I'll realize it's going to be complex, decide how that piece of code could be turned into a function by deciding what to send in, and what to send out, and then put that call in and finish writing the original function. Then I'll write the (so far) imaginary function which contains the complex bit.
So recursion is just realizing that I can do the complex bit by calling the current function!
Of course, this sometimes means that the function signature needs to change, to (say) include a collecting list or something. But that's the general idea.
I'm not sure if this has ever helped anyone :-)
- meken 6y agoYeah, top-down programming is useful for understanding recursion, e.g. "wishful thinking". I think Jerry Sussman describes this beautifully in this SICP lecture snippet https://youtu.be/amf5lTZ0UTc?t=3501 https://youtu.be/amf5lTZ0UTc?t=3501 "...but since I know [the function X], by wishful thinking, will produce the simplified result, then I don't have to think about it anymore. I've used it. I've used it in a reasonable way. I will get a reasonable answer." I didn't understand recursion too well until finishing chapter 2 of SICP.