Can I make a Function Call Itself?

This is called recursion, an important technique in computer science. Note that each call allocates on the stack, so if you go too deep you will get a stack overflow (which gave its name to a famous website).

julia> counter = 0;

julia> function f()
           global counter += 1
           f()
       end;

julia> f()
ERROR: StackOverflowError:
Stacktrace:
 [1] f()
   @ Main ./REPL[12]:2
 [2] f() (repeats 79980 times)
   @ Main ./REPL[12]:3

julia> counter
130830

So f was able to call itself recursively 130830 times before the stack grew too big.

3 Likes