优化语法在F#异步映射序列 [英] Optimizing syntax for mapped async sequences in F#

查看:105
本文介绍了优化语法在F#异步映射序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出有效的语法如下F#前pression。比方说,我有一个F#异步计算:

I am trying to figure out efficient syntax for the following F# expression. Let's say I have an F# async computation:

let asyncComp n = async { return n }

它有一个签名一 - >异步<'A> 。现在,我定义这些序列:

It has a signature 'a -> Async<'a>. Now I define a sequence of those:

let seqOfAsyncComps = 
    seq {
        yield asyncComp 1
        yield asyncComp 2
        yield asyncComp 3
    }

现在我有序列&LT的项目; LT异步&;&INT GT;&GT; 。如果我想从 SEQ&LT元素异步映射什么;异步&LT; INT&GT;&GT; 以次&LT;异步&LT; INT&GT;&GT; 。这是行不通的:

Now I have an item of seq<Async<int>>. What if I want to asynchronously map the elements from seq<Async<int>> to seq<Async<int>>. This won't work:

let seqOfAsyncSquares =
    seqOfAsyncComps |> Seq.map (fun x -> x * x) // ERROR!!!

当然, X 异步&LT; INT&GT; ,我要提取的 INT 第一,所以我可以做以下代替:

Of course, x is Async<int>, I have to extract an int first, so I can do the following instead:

let seqOfAsyncSquares =
    seqOfAsyncComps |> Seq.map (fun x -> async { 
                                            let! y = x
                                            return y * y }) // OK

这工作正常,但语法是笨拙。它带走了F#紧凑,如果我想链数 SEQ 处理我必须做的每一个地图,过滤器 ITER

This works fine but the syntax is clumsy. It takes away F# compactness, and if I want to chain several seq processing I have to do the same trick in every map, filter or iter.

我怀疑有可能是一个更有效的语法来处理与包括异步计算的序列。

I suspect there might be a more efficient syntax to deal with sequences that consist of async computations.

推荐答案

您可以使用 Async.map (即我只有现在公然的从托马斯Petricek )被盗:

You could use Async.map (that I've only now blatantly stolen from Tomas Petricek):

module Async =
  let map f workflow = async {
    let! res = workflow
    return f res }

let seqOfAsyncSquares' =
    seqOfAsyncComps |> Seq.map (Async.map (fun x -> x * x))

如果您评价它,你会看到,它似乎产生预期的结果:

If you evaluate it, you'll see that it seems to produce the expected outcome:

> seqOfAsyncSquares' |> Async.Parallel |> Async.RunSynchronously;;
val it : int [] = [|1; 4; 9|]

这篇关于优化语法在F#异步映射序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆