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

Compiler enforced tail calls #223

Open
robinheghan opened this issue Sep 12, 2023 · 0 comments
Open

Compiler enforced tail calls #223

robinheghan opened this issue Sep 12, 2023 · 0 comments
Labels
language proposal proposal of a major feature to the language

Comments

@robinheghan
Copy link
Member

Gren will correctly optimize tail-recursive functions to avoid the possibility of stack overflow exceptions.

countDown : Int -> Int
countDown value =
  if value < 1 then 
    0
  else
    countDown (value - 1)

In the example above, countDown is recognized by the compiler as tail-recursive, and will be compiled into a while loop that doesn't consume stack space. However, if you were to somehow get this wrong then you'd get no warning from the compiler that your function isn't stack safe. For beginners, it's also not always apparent what is and isn't stack safe.

This proposal introduces the recur keyword, which is a hint to the compiler that the function is meant to be stack safe in the face of recursion. The compiler can then check, and potentially fail, if that doesn't turn out to be the case.

countDown : Int -> Int
countDown value =
  if value < 1 then
    0
  else
    recur (value - 1)

The recur keyword can also work in the face of optimizations such as tail recursion modulo cons, which makes it a bit harder to understand all the potential cases where recursion is stack safe.

@robinheghan robinheghan added language proposal proposal of a major feature to the language accepted The issue has been reviewed and accepted for implementation labels Sep 12, 2023
@robinheghan robinheghan removed the accepted The issue has been reviewed and accepted for implementation label Jun 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
language proposal proposal of a major feature to the language
Projects
None yet
Development

No branches or pull requests

1 participant