gpt4 book ai didi

.net - 如何在 F# 中使用 System.Threading.Tasks?

转载 作者:行者123 更新时间:2023-12-01 08:08:04 28 4
gpt4 key购买 nike

我正在学习 F#。最近,我读到有关 .NET 4.5 任务方面的改进。因此,我看了一下如何在 F# 中使用它。在 fsi 中:

use System.Threading.Tasks
Parallel.ForEach([1;2],fun x->x+1);;

给出了很多错误。

另外,在Fsharp核心库的源代码中。我看到了:

module Parallel =
open System.Threading.Tasks

[<CompiledName("Choose")>]
let choose f (array: 'T[]) =
checkNonNull "array" array
let inputLength = array.Length
let lastInputIndex = inputLength - 1

let isChosen : bool [] = //(Deliberately offside to avoid scrollbars)
Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength
let results : 'U [] =
Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength

但是,我无法使用 Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked。为什么?我得到了:

error FS1092: The type 'Array' is not accessible from this code location.

最佳答案

您对 ForEach 方法的使用令人困惑,因为您的 lambda 函数返回一个结果。 ForEach 操作可用于对输入中的所有元素执行一些强制性操作,因此 lambda 函数应返回 unit。以下将正常工作:

open System.Threading.Tasks 

Parallel.ForEach([1;2], fun x->
printfn "%d" (x+1)) |> ignore

我还添加了 ignore,因为 ForEach 作为结果返回了一些值(我们不使用它)。

关于 F# 核心库代码 - 代码被编译为 F# 核心库的一部分,因此它可以使用一些未在公共(public) API 中公开的内部函数,因此您不能使用它们。在您的情况下,您需要使用 Array.zeroCreate 而不是 Array.zeroCreateUnchecked

关于.net - 如何在 F# 中使用 System.Threading.Tasks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8401953/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com