You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I might be missing something but I couldn't find this in documentation or in tracker.
Is there a way in CS to give a function an explicit name, or are all functions effectively anonymous?
This is kind of important for recursion
fact = (n) -> if n == 0 then 1 else n * fact(n - 1)
new_fact = fact
fact = 'something else'
new_fact 4 # Error
The text was updated successfully, but these errors were encountered:
CS doesn't currently support JS-style function names, because of concerns about memory leaks in the IE6 garbage collector. I'll try to find the link.
This has been discussed as a potential problem for debugging, but is it really an issue for recursion? How often do you redefine a self-referring function within the scope of its own declaration? It seems like a pretty confusing move.
If you really need to, it's still possible to create a mini-scope just to hold the function's named self-reference:
scope = (block) -> block()
fact = scope ->
self = (n) -> if n == 0 then 1 else n * self(n - 1)
new_fact = fact
fact = 'something else'
new_fact 4 # 24
Or you can just use arguments.callee:
fact = (n) -> if n == 0 then 1 else n * arguments.callee(n - 1)
new_fact = fact
fact = 'something else'
new_fact 4 # 24
I wouldn't redefine a self-referring function deliberately. I'm just a little concerned that the lack of named functions makes recursive functions somewhat unsafe. I was going to propose to introduce some keyword (for example recur) to allow function to reference itself. It would also allow to write recursive function literals
fact4 = ((n) -> if n == 0 then 1 else n * recur(n - 1))(4)
However your scope idiom seems good enough, so I'm not sure if it's worth the effort. Although, to be totally safe one would have to use this idiom for every recursive function.
I might be missing something but I couldn't find this in documentation or in tracker.
Is there a way in CS to give a function an explicit name, or are all functions effectively anonymous?
This is kind of important for recursion
The text was updated successfully, but these errors were encountered: