“Necessary” Uses of Recursion in Imperative Languages

后端 未结 9 1033
独厮守ぢ
独厮守ぢ 2020-12-17 17:10

I\'ve recently seen in a couple of different places comments along the lines of, \"I learned about recursion in school, but have never used it or felt the need for it since

相关标签:
9条回答
  • 2020-12-17 17:55

    It's all about the data you are processing.

    I wrote a simple parser to convert a string into a data structure, it's probably the only example in 5 years' work in Java, but I think it was the right way to do it.

    The string looked like this:

    "{ index = 1, ID = ['A', 'B', 'C'], data = {" +
       "count = 112, flags = FLAG_1 | FLAG_2 }}"
    

    The best abstraction for this was a tree, where all leaf nodes are primitive data types, and branches could be arrays or objects. This is the typical recursive problem, a non-recursive solution is possible but much more complex.

    0 讨论(0)
  • 2020-12-17 17:55

    It was said "anything tree". I may be too cautious, and I know that stacks are big nowadays, but I still won't use recursion on a typical tree. I would, however, do it on a balanced tree.

    0 讨论(0)
  • 2020-12-17 17:58

    In my opinion, recursive algorithms are a natural fit when the data structure is also recursive.

    def traverse(node, function):
        function(this)
        for each childnode in children:
            traverse(childnode, function)
    

    I can't see why I'd want to write that iteratively.

    0 讨论(0)
提交回复
热议问题