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

Guarded Tail Call Optimisation #533

Closed
Kesanov opened this issue Oct 24, 2019 · 0 comments
Closed

Guarded Tail Call Optimisation #533

Kesanov opened this issue Oct 24, 2019 · 0 comments
Labels
p-medium Should be completed in the next few sprints

Comments

@Kesanov
Copy link
Contributor

Kesanov commented Oct 24, 2019

Summary

Guarded call is just a constructor in tail call position: Constructor a b c ... n
The interesting observation is that the the data type can be allocated before calling a b c ... like this:

result   = Constructor null null null ..
a' (k -> result.1 = k)
b' (k -> result.2 = k)
...
n' (k -> result.n = k)

where
n' args k = k (n args) = { result.n = n args } -- after inlining k

This allows us to choose the most expensive term (a | b | c ..) and make it a tail call.

As a consequence, guarded tree recursion allocates one stack frame less on each recursive call.
And more importantly linear recursion like map, take, filter, concat, Trie.insert becomes tail recursive:

map node fun Nil = 
    node.next = Nil
map node fun (Cons x xs) =
    node.next = Cons (fun x) null
    map node.next fun xs

Value

  • faster and stackoverflow-safe recursion (when linear & guarded)
  • users don't have to write mutable code, immutable code is easier to optimize

Specification

  • Implement static recursion detection.
  • Make sure constructors get inlined into higher order functions.
  • Implement the above described transformation.

Acceptance Criteria & Test Cases

Every linear guarded recursion becomes tail call recursive. Even when implemented with higher order function. For example:

map f = foldr (a -> Cons (f a)) Nil
@iamrecursion iamrecursion changed the title Guarded tail call optimization. Guarded Tail Call Optimisation Nov 6, 2019
@iamrecursion iamrecursion transferred this issue from another repository Jun 23, 2020
@joenash joenash added Category: Compiler p-medium Should be completed in the next few sprints labels Jun 23, 2020
This was referenced Jun 23, 2020
@wdanilo wdanilo closed this as completed Apr 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
p-medium Should be completed in the next few sprints
Projects
None yet
Development

No branches or pull requests

3 participants