-
Notifications
You must be signed in to change notification settings - Fork 5
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
tailrec
to enforce tail recursion
#11
Comments
Agree, things like this are useful. One thing I'd like is to push these to metadata/attribute level and not have them occupy a keyword. |
F# has a rec keyword. Why not re-use it? |
@aloisdg The |
Yep, and F# doesn't have this feature :( |
Making it an attribute will require allowing attributes on local functions, because tailrecs are rarely used as top level function, mostly they're inner functions. Take F# list module as an example (search for "loop"). Attributes on local functions will look too heavyweight |
How so? Allowing attributes everywhere seem simply reasonable. func fact(n: int32): int32 {
#[TailRecursive]
func f(acc: int32, n: int32): int32 =
if (n == 0) acc
else f(n * acc, n - 1);
return f(1, n);
} Seems quite elegant IMO. |
One thing to make sure of: iirc the CLR does not guarantee that it can always |
F# does it on IL level, and that's how I want to have it too. |
And because the clr doesn't guarantee |
My point is that we don't need to emit IL's tail call at all. We can turn our recursion into a loop, basically, and only then compile it to IL |
You can, but that (as far as I know) isn't how F# does it. It uses |
It emits tail very rarely. Simple example for turning a rec into loop That's exactly why unlike C#, it can almost guarantee TCO for tailrec. |
Less elegant than F# version let fact n =
let rec loop acc x =
if x = 0
then acc
else loop (acc * x) (x - 1)
loop 1 n Making it an attribute will take same space, as required for entire function definition: #[TailRecursive]
let loop acc x = |
If tail recursion is impossible, give an error.
Stolen from Kotlin.
The text was updated successfully, but these errors were encountered: