by dvt · 11y ago · 0 comments
> Do not write recursive procedures. Do not use procedures recursively.
I've probably failed 90% of recursion "gotcha'" questions I've had during interviews. It's my uninformed opinion that recursion is uninteresting and unintuitive. This is why whenever I encounter it, I either ignore it or refactor it. I'm exaggerating, of course, but I really do hate it. There are some very interesting theoretical applications, however. The article briefly mentions Lambda Calculus (which I love) where I've always enjoyed playing with the divergent Omega combinator[1]:
Ω = (λx. x x) (λx. x x)
I'm may be entirely too stupid to appreciate the beautiful intricacies of recursive programming, but I do think that recursive programming can be susceptible to some unique bugs, such as exceeding stack/heap, that are very difficult to notice prima facia (more difficult than when the same is done via procedural code, at least).
[1] http://www.seas.upenn.edu/~cis500/cis500-f06/lectures/0925-2...
Other stuff, not so much. Consider the Fibonacci Sequence written recursively.
If you are just doing a simple search, maybe you don't need to keep that whole stack around. An iterative approach makes a lot of sense. If you are building a map of the tree and you're not even sure what scale to make it, you might want to reserve judgement about the supertree while you explore some sub trees so you might be glad that stack is there, and you might profit from thinking about that situation as recursion.
But the answer is: yes, a lot of things you do with trees make a lot of sense as simple procedures.
"We have a sequential block of memory, and we want to store a sequence in it... hrm... I know, why don't we put the first element in this struct, and... I'll deal with the rest of the items elsewhere."
Suddenly linked lists (doubly-linked) are looking pretty intuitive :)
Going down this route would probably result in a contiguous linked list. You can argue that this is still a linked list, but I still find it conceptually more obvious. For a billion elements, it's probably also a lot faster, too.
Rule 4 (recursion)
There shall be no direct or indirect use of recursive function calls.
[MISRA-C:2004 Rule 16.2; Power of Ten Rule 1]
The presence of statically verifiable loop bounds and the absence of recursion
prevent runaway code, and help to secure predictable performance for all
tasks. The absence of recursion also simplifies the task of deriving reliable
bounds on stack use. The two rules combined secure a strictly acyclic function
call graph and control-flow structure, which in turn enhances the capabilities
for static checking tools to catch a broad range of coding defects.
[0] http://lars-lab.jpl.nasa.gov/JPL_Coding_Standard_C.pdf The coding rules defined here primarily target the development of mission
critical flight software written in the C programming language. This means
that the rules are focused on embedded software applications, which
generally operate under stricter resource constraints than, e.g., ground
software.
I don't think it's at all surprising that the coding standards governing critical software running in resource-constrained environments should be so conservative. But I also don't know that the priorities motivating those standards generalize well to what most programmers do for a living.Only if you're sloppy about the inputs given to the recursive code.
Recursion isn't magical. It's deterministic, and is a function of some aspect of the input values. (Corollary: If it isn't, what the fuck are you doing?)
So NASA decided to solve the stack growth problem by limiting recursion. (Zero is a limit.) It could have done the other thing and limited inputs to recursive code, which would have required more careful code analysis (static and dynamic) to figure out what the limits should be. It's an understandable decision, but don't forget it's a trade-off, and one that could have gone another way.
So any recursive algorithm using tail-calls would be better implemented as a for/while loop in embedded C contexts, the performance will be similar (should actually be better) and the memory is now constant instead of increasing.
Any recursive algorithms that can't use tail-calls, I'm honestly not thinking of common situations for these in an embedded context. Perhaps traversing certain data structures, but you can probably find a different data structure that will be sufficiently efficient and not require non-tail-calls. Even with sorting, if you have a small, fixed sized array you could implement a sorting network. If it's too large for that to be feasible in code, it's probably still a small enough array that insertion sort is efficient.
I don't see the trade-off.
On one hand (if you allow recursion) you need "more careful code analysis".
On the other hand, if you don't allow it, you don't lose anything. You can write the algorithm in another way, and it would be just as fast and easier to reason about.
So what's the tradeoff? It's not like recursion brings some benefit that you lose if you disallow it.
Recursion is the use of the built in stack data structure that the compiler manages for you.
If you are working your way through a data set with a well determined end state that you incrementally approach (be it the end of the list, or getting closer and closer to finding a value in a tree), and you have a need to backtrack, then recursion is a good way to solve the problem.
All recursive code can be rewritten to be non-recursive, you just keep track of your own stack data structure. This can be either not that much work, or a major pain, depending on the exact problem.
Bull, a function that is not primitive recursive cannot be rewritten to be non recursive.
Sources: https://en.wikipedia.org/wiki/Ackermann_function https://www.youtube.com/watch?v=i7sm9dzFtEI
It's my informed opinion that I personally often find unintuitive things to be uninteresting, because thinking about them is less rewarding.
I wouldn't take your lack of interest to be a sign of your lack of intelligence so much as a different distribution of intuition.
Haskell tutorials usually advise against explicit recursion, instead favouring combinations of map, filter etc. as the best choice, and failing that use foldl', foldr etc. With explicit recursion only being used if you really have a good reason.
I want to take my JSON, and store it in Dynamo.
I need to convert every object object embedded in my top object to a {"M" : {...}} structure, and every array/list to a {"L" : [...]} structure. So something like - {"a" : {"b" : [1]}} should become {"a" : {"M" : {"b" : {"L" : ["N" : "1"]}}}}.
The easiest way to write one function that can handle that in a generic way, no matter how complicated the data structure (barring hitting the stack limit), is recursion.
Ever?
Those are trees. Want to walk the UI to find an element? Trees. Want to manipulate the DOM? Trees.
Walk a file system?
Write a file system?
Trees and trees.
Furthermore, part of our indexing needed to follow imports to find the canonical name of a value, which is a problem very well suited to a recursive solution.
You may not have encountered these situations where recursion and trees have to be dealt with, but they absolutely exist.
I'm all for code-reuse and componentization but common... recursion is programming 101!