A question about Return
-
So yesterday I had the case where I used return in Fuze its used to return a value from a function i think. I made the discovery that you can even return the function it self but the problem is that if you do this you got in something like an endless loop so my question is is there a good reson to return the function it self
-
I don't think you returned the function, but instead returned the result of the function. This would mean you have a function that calls itself (not returns itself).
Such behavior is called
recursion
and can be useful in all sorts of algorithms, but with recursion you need to keep in mind that yourcall stack
should never exceed the maximum. That would lead to an error.A typical example for recursion would be factorial (in math the exclamation-mark is used for this). For example 5 factorial would be
5! = 5*4*3*2*1 = 120
.A recursive function to calculate this could be:
function fact(n) int result = 1 if n >= 1 then result = n * fact(n - 1) endif return result
-
That factorial looks like it would be useful for those ’how many triangles can you see - 99% of people will get this wrong!’ facebook memes...
-
@PB____ Do you tried return fact()
-
Again, you would NOT be returning the function itself. That would return the result of calling the function.
-
@petermeisenstein as far as I know, functions in FUZE only have one return statement (at the end of the function) and do not have short circuiting either. So if you call the function itself within the return statement, it always gets called. So it would always result in an error related to the call stack. I've not tried it, but I'm pretty sure that's what happens.
To use recursion in FUZE, you will always need a condition where the function stops calling itself.
In some languages you may be able to have infinite recursion by calling the next function asynchronously outside of the call stack. But even then you need to be sure that that's something you want to do.
I've not used timers for anything serious in Fuze myself (because I don't trust them), but if it would be possible to create a timer that calls a function with a function scoped variable as argument. Then it might be possible to use such a mechanism to realize near infinite asynchronous recursion. But my guess would be that that's not supported, and it's probably a bad idea anyway.
EDIT: such a pattern would require the support for closure (where a function-scoped variable outlives the lifespan of the function call itself), that would make things like garbage collection more complex.
-
@PB____ Ok thanks for the answer and yes it goes in to an endless trigerring if you return the function