FSharp.Control.TaskSeq icon indicating copy to clipboard operation
FSharp.Control.TaskSeq copied to clipboard

Consider tail recursion

Open abelbraaksma opened this issue 3 years ago • 6 comments

We've removed the tail recursion because it was hard to consolidate it into yield! (it was instead done with return!, which has no place in taskSeq).

However, today I helped someone with some code that he considered for taskSeq which had the following approach:

let getPoliciesAsync policyid =
    asyncSeq{
        use connection = new NpgsqlConnection(npgsqlConnectionStringBuilder.ConnectionString)
        use command = new NpgsqlCommand($"SELECT policy_data FROM policy.tbl_policy where policy_id = {Sql.uuid policyid};", connection)
        let! reader = command.ExecuteReaderAsync() |> Async.AwaitTask
        let rec someRec() = asyncSeq{
            let! rowExists = reader.ReadAsync() |> Async.AwaitTask
            if rowExists then
                yield {| dt1 = reader.GetString(0) |}
                yield! someRec()
        }
        yield! someRec()
    } |> AsyncSeq.toAsyncEnum

As you can see, it uses asyncSeq, but also: it is recursive. The same approach with taskSeq would likely be more performant, however, if there are a lot of rows, this becomes problematic. This code can be rewritten with a loop, though.

@dsyme, sharing this with you in case we want to revisit this at some point.

abelbraaksma avatar Nov 01 '22 11:11 abelbraaksma

Yes, this should be rewritten with a loop

dsyme avatar Nov 01 '22 22:11 dsyme

@abelbraaksma BTW I think I am going to prioritise an F# 8 addition to allow builders to specify ReturnFromTailcall or YieldFromTailcall methods.

dsyme avatar Nov 05 '22 16:11 dsyme

@dsyme that would certainly simplify an addition like this, and would also allow task to support tail calls. Awesome! We can do some early-adoption testing here through TaskSeq.

abelbraaksma avatar Nov 06 '22 15:11 abelbraaksma

See https://github.com/fsharp/fslang-suggestions/issues/1006 instead.

abelbraaksma avatar Oct 29 '23 18:10 abelbraaksma