函数列表上的映射的F#声明中的错误FS0752 [英] Error FS0752 in F# declaration of a map over list of functions

查看:55
本文介绍了函数列表上的映射的F#声明中的错误FS0752的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在相应值的列表上执行函数列表:

I would like to execute a list of functions over a list of corresponding values:

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;;  

结果:

  seq { for i in 0..1 do yield async { return list1.[i] list2.[i] } }
----------------------------------------------^^^^^^^^^

stdin(213,49):错误FS0752: 运算符'expr.[idx]'已被使用 基于的不确定类型的对象 此计划之前的信息 观点.考虑添加其他类型 约束

stdin(213,49): error FS0752: The operator 'expr.[idx]' has been used an object of indeterminate type based on information prior to this program point. Consider adding further type constraints

我想执行:pmap2 conslist [5; 8] ;; (并行)

I would like to execute: pmap2 conslist [5;8];; (in parallel)

推荐答案

如果要使用随机访问,则应使用数组.可以对列表元素进行随机访问,但效率不高(需要从头开始遍历列表).使用数组的版本如下所示:

If you want to use random access then you should use arrays. Random access to elements of list will work, but it is inefficient (it needs to iterate over the list from the start). A version using arrays would look like this:

// 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

但是,您也可以使用Seq.zip函数重写该示例以使其适用于任何序列(包括数组和列表).我认为此解决方案更优雅,并且不会强迫您使用命令式数组(并且不存在性能劣势):

However, you can also rewrite the example to work with any sequences (including arrays and lists) using the Seq.zip function. I think this solution is more elegant and it doesn't force you to use imperative arrays (and it doesn't have the performance disadvantage):

// 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

这篇关于函数列表上的映射的F#声明中的错误FS0752的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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