Skip to content

Optimizing non-tail recursions for sequences #18213

@AlexRadch

Description

@AlexRadch

F# now optimizes tail recursion when generating sequences.

let rec tail b e = seq {
    if b <= e then
        yield b
        yield! tail (b+1) e
}

The above tail recursion will be successfully optimized and the performance will be linear.

let rec head b e = seq {
    if b <= e then
        yield! head b (e-1)
        yield e
}}

At the same time, the above head recursion will not be optimized, and the performance will be quadratic.

To optimize tail recursion, the GenerateNext method can return the flag (2) to go to the next iterator and thus the tail recursion execution speed will become linear rather than quadratic.

I propose adding to this method the ability to call the next iterator and return execution to the current iterator. Flag 3 will call the next iterator and return execution to the current iterator. This will optimize the speed of all simple recursions to linear, and not just simple tail recursions.

To support the ability to call the next iterator and return to the current one, add a stack of iterators in the GeneratedSequenceBase<int> class. Adding a stack of iterators will allow you to optimize all types of simple recursions, not just tail ones.

Metadata

Metadata

Assignees

No one assigned

    Projects

    Status

    New

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions