Answer the question
In order to leave comments, you need to log in
Recursion, why is it needed, and do you use it?
When studying one of the programming languages, I asked myself this question: why do we need recursion, if you can always do without it?
Really if I learn how to use it and come to a good office, then everyone there (especially juniors) will understand my code? - This is the main question .
Answer the question
In order to leave comments, you need to log in
The simplest example: building a tree of elements with an indefinite nesting level.
Is it possible that if I learn how to use it and come to a good office, everyone there (especially juniors) will understand my code?
why do you need recursion if you can always do without it?
fun ConvertJsonElementToObject(element: JsonElement): Object {
return match(element.type) {
Number(num) -> num as Object,
String(str) -> str as Object,
Array(elements) -> elements.map(ConvertJsonElementToObject) as Object,
Object(dict) -> dict.mapValues(ConvertJsonElementToObject) as Object,
Null -> null as Object
}
}
If several recursive calls are made inside the function, then the loop + stack option will look complicated and the aforementioned juns will feel difficult to understand it. Or, for example, a case when there is a mutual recursion of two or more functions - there you will have to redraw the code somehow, depending on the situation.
The non-recursive option should definitely be used when you can do without a stack, as in the hackneyed example of factorial calculation. The same is true when there is a non-zero probability that there will be a stack overflow: for example, a function works with an arbitrary binary tree, and can receive a very unbalanced tree of high height as input. There are also other special cases. Let's say a depth-first traversal of the graph: if you make it non-recursive, then you can easily replace the stack with a queue in the function and get a traversal in width, or even a priority queue, then there will be a "search by cost criterion"
In functional programming (Haskell) there are no loops, only recursion.
Really if I learn how to use it and come to a good office, then everyone there (especially juniors) will understand my code? - This is the main question.For example, the directory traversal function is usually implemented recursively, because through the loop it is not always convenient and readable, plus it is more difficult to implement, you can try to implement the bypass of directories through the loop and through recursion and compare.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question