Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question. Function names; recursion. #732

Closed
akva opened this issue Sep 29, 2010 · 3 comments
Closed

Question. Function names; recursion. #732

akva opened this issue Sep 29, 2010 · 3 comments
Labels

Comments

@akva
Copy link

akva commented Sep 29, 2010

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
@hen-x
Copy link

hen-x commented Sep 29, 2010

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

@akva
Copy link
Author

akva commented Sep 29, 2010

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.

@michaelficarra
Copy link
Collaborator

Javascript has arguments.callee for self-reference (except in ES5). Check out the Y combinator if you're really worried about this non-issue issue.

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants