필터 지우기
필터 지우기

Calling the same function from within the function??

조회 수: 12 (최근 30일)
Marc
Marc 2013년 10월 9일
댓글: Marc 2013년 10월 9일
So I ran into this very interesting file from the file exchange...
Where the function calls itself around line 140 (its between 138 thru 144 as I started to play with some things...). This was wild to me. I have never attempted this and was wondering if there are other examples out there.
Does this work for C++ or Fortran?
Comments? Why is this blowing my mind?

채택된 답변

Walter Roberson
Walter Roberson 2013년 10월 9일
This is called "recursion", and it is legal in most programming languages.
Every linear procedure can be rewritten as a recursive procedure.
Every recursive procedure can be rewritten as a linear procedure, provided that sufficient dynamic memory allocation is permitted. Doing so might be awkward and might require a lot of extra memory, but it is always possible.
There is a subset of recursion called "tail recursion" that can be quite efficient to execute.
Recursive functions are very important in theoretical computer science. The theory of what can be deterministically computed talks about "Primitive Recursive Functions"
  댓글 수: 1
Jos (10584)
Jos (10584) 2013년 10월 9일
Just curious, is recursion (explicitly) illegal in some programming languages?

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

ES
ES 2013년 10월 9일
It is mere recursion supported by most high level languages.

Jan
Jan 2013년 10월 9일
I'm convinced that recursion does not blow your mind. You only have to get familiar with it. Then it is useful in many situations. A standard example for a recursive definition is the Fibonacci sequence (ask WikiPedia for details). And this is also a good example, why recursive functions are in many cases not efficient.
Another typical example are "Divide and Conquer" algorithms: The program splits the problem into two halves and provide both as inputs to itself until the problems are such small, that a solution is trivial. E.g. you can find the maximum value of a vector by splitting the vector until both parts have a single element only. This is a nice solution, but not fast.
  댓글 수: 1
Marc
Marc 2013년 10월 9일
Your right, recursion does not blow my mind (albiet, I completely forgot I had learned it, ever....). I guess the way it was employed in the above example was the first time in over 10+ years I have seen it used.
Out of sight, out of mind.

댓글을 달려면 로그인하십시오.


Simon
Simon 2013년 10월 9일
Hi!
For Fortran77 programs recursive functions (or subroutines) are not possible, as a standard compiler gives you a compile time error. Altough there are ways to trick the compiler ...
Fortran90/95 supports recursion as long as the specific function/subroutine is explicitly labeled as a recursive function.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by