簡體   English   中英

如何在 F# 中創建遞歸異步 function?

[英]how can I make a recursive async function in F#?

我有以下內容:

let getCandlesFrom (exchange: IExchange) (instrument: Instrument) (interval: TimeSpan) (fromTime: DateTime) =
    let rec get (c: CandleData array) (f: DateTime) =
        let now = DateTime.UtcNow
        //info $"requesting {f} - {now}"
        let candles = exchange.GetCandles(instrument, interval, f, now)
        if candles.IsError then
            failwith candles.GetError.Describe
        else
            //info $"received data {candles.Get.[0].Timestamp} - {candles.Get.[^0].Timestamp}"
            let c = Array.append c candles.Get
            if c.[^0].Timestamp < now - interval then
                get c (c.[^0].Timestamp + interval)
            else
                c

    get [||] fromTime

我想移動這條線:

let candles = exchange.GetCandles(instrument, interval, f, now)

到異步調用:

let! candles = exchange.GetCandlesAsync(instrument, interval, f, now)

但是如果我將整個 function 包裝在一個異步塊中,則遞歸 function 不會編譯,我會收到此錯誤:

DataSource.fs(14, 13): [FS0588] 這個 'let' 后面的塊未完成。 每個代碼塊都是一個表達式,並且必須有一個結果。 'let' 不能是塊中的最后一個代碼元素。 考慮給這個塊一個明確的結果。

我沒有看到您的代碼產生錯誤,但您一定忘記了一些東西(在let之后) - 這應該有效:

let getCandlesFrom (exchange: IExchange) (instrument: Instrument) (interval: TimeSpan) (fromTime: DateTime) =
    let rec get (c: CandleData array) (f: DateTime) =
        asnyc {
            let now = DateTime.UtcNow
            //info $"requesting {f} - {now}"
            let! candles = exchange.GetCandlesAsync(instrument, interval, f, now)
            if candles.IsError then
                return (failwith candles.GetError.Describe)
            else
                let c = Array.append c candles.Get
                if c.[^0].Timestamp < now - interval then
                    return! get c (c.[^0].Timestamp + interval)
                else
                    return c
    }
    get [||] fromTime

注意returnreturn! 對於遞歸調用 - 你需要那些

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM