F#Parallel.ForEach无效的方法重载

时间:2013-04-25 23:18:10

标签: f# task-parallel-library parallel.foreach

创建此表单的Parallel.ForEach表达式:

    let low = max 1 (k-m)
    let high = min (k-1) n
    let rangesize = (high+1-low)/(PROCS*3)

    Parallel.ForEach(Partitioner.Create(low, high+1, rangesize), (fun j ->

            let i = k - j
            if x.[i-1] = y.[j-1] then
                a.[i] <- b.[i-1] + 1
            else 
                a.[i] <- max c.[i] c.[i-1] 
        )) |> ignore

导致我收到错误:方法'ForEach'没有重载匹配。但是,我使用的是Parallel.ForEach<TSource>方法(Partitioner<TSource>, Action<TSource>),这似乎对我而言。我错过了什么吗?

编辑:我试图获得与下面代码相同的结果(不使用分区程序):

let low = max 1 (k-m)
let high = min (k-1) n
let rangesize = (high+1-low)/(PROCS*3)

let A = [| low .. high |]
Parallel.ForEach(A, fun (j:int) ->

    let i = k - j
    if x.[i-1] = y.[j-1] then
        a.[i] <- b.[i-1] + 1
    else 
        a.[i] <- max c.[i] c.[i-1] 
    ) |> ignore

1 个答案:

答案 0 :(得分:3)

您确定已经打开了所有必需的命名空间,您所使用的所有值(lowhighPROCS)都已定义,并且您的代码不会意外地重新定义某些您正在使用的名称(如Partitioner)?

我使用此代码创建了一个非常简单的F#脚本,它似乎工作正常(我重构了代码以创建一个名为p的分区程序,但这不会影响行为):

open System.Threading.Tasks
open System.Collections.Concurrent

let PROCS = 10
let low, high = 0, 100

let p = Partitioner.Create(low, high+1, high+1-low/(PROCS*3))
Parallel.ForEach(p, (fun j ->
    printfn "%A" j  // Print the desired range (using %A as it is a tuple)
)) |> ignore

j实际上是一对类型int * int非常重要,因此如果正文以错误的方式使用它(例如int),您将获得错误。在这种情况下,您可以向j添加类型注释,并在其他地方获得更有用的错误:

Parallel.ForEach(p, (fun (j:int * int) ->
    printfn "%d" j // Error here, because `j` is used as an int, but it is a pair!
)) |> ignore

这意味着如果您想对原始范围内的所有j值执行某些操作,则需要编写如下内容:

Parallel.ForEach(p, (fun (loJ, hiJ) ->
  for j in loJ .. hiJ - 1 do // Iterate over all js in this partition
    printfn "%d" j           // process the current j
)) |> ignore

除此之外,我想Partitioner.Create的最后一个参数实际上应该是(high+1-low)/(PROCS*3) - 你可能想要除以步骤的总数,而不仅仅是low值。