我想在相应值列表上执行函数列表:
let f1 x = x*2;;
let f2 x = x+70;;
let conslist = [f1;f2];;
let pmap2 list1 list2 =
seq { for i in 0..1 do yield async { return list1.[i] list2.[i] } }
|> Async.Parallel
|> Async.RunSynchronously;;
Run Code Online (Sandbox Code Playgroud)
结果:
seq { for i in 0..1 do yield async { return list1.[i] list2.[i] } }
----------------------------------------------^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
stdin(213,49):错误FS0752:运算符'expr.[idx]'已被用作基于此程序点之前的信息的不确定类型的对象.考虑添加其他类型约束
我想执行:pmap2 conslist [5; 8] ;; (在平行下)
如果要使用随机访问,则应使用数组.对列表元素的随机访问将起作用,但效率低下(它需要从头开始迭代列表).使用数组的版本如下所示:
// Needs to be declared as array
let conslist = [|f1; f2|];;
// Add type annotations to specify that arguments are arrays
let pmap2 (arr1:_[]) (arr2:_[]) =
seq { for i in 0 .. 1 do
yield async { return arr1.[i] arr2.[i] } }
|> Async.Parallel |> Async.RunSynchronously
Run Code Online (Sandbox Code Playgroud)
但是,您也可以使用该Seq.zip函数重写该示例以使用任何序列(包括数组和列表).我认为这个解决方案更优雅,它不会强迫您使用命令式数组(并且它没有性能劣势):
// Works with any sequence type (array, list, etc.)
let pmap2 functions arguments =
seq { for f, arg in Seq.zip functions arguments do
yield async { return f arg } }
|> Async.Parallel |> Async.RunSynchronously
Run Code Online (Sandbox Code Playgroud)