What is a practical difference between a loop and recursion

前端 未结 9 2729
无人共我
无人共我 2021-02-19 22:42

I am currently working in PHP, so this example will be in PHP, but the question applies to multiple languages.

I am working on this project with a fiend of mine, and as

9条回答
  •  庸人自扰
    2021-02-19 22:50

    Often, a problem is easier expressed using recursion. This is especially true when you talk about tree-like data structures (e.g. directories, decision trees...).

    These data structures are finite in nature, so most of the time processing them is clearer with recursion.

    When stack-depth is often limited, and every function call requires a piece of stack, and when talking about a possibly infinite data structure you will have to abandon recursion and translate it into iteration.

    Especially functional languages are good at handling 'infinite' recursion. Imperative languages are focused on iteration-like loops.

提交回复
热议问题