简体   繁体   中英

F# and PLINQ extension methods

While digging deeper into the latest release of F# I tried to have it interacting with PLINQ. I've noticed, however, that the two don't play very nice together code-wise. In fact it didn't seem possible to write code such as the following:


open System.Linq
let someArray = [|"abc"; "def"|]
someArray.AsParallel().Count(new Func<_,_>(fun s -> s.Length = 3))

because the extension methods for ParallelQuery contained in the System.Linq.ParallelEnumerable class didn't seem to get picked up by F#.
I wouldn't be surprised if there were no support for extension methods at all, but since I can access the someArray.Count extension method defined for IEnumerable I wonder why can't I access those of PLINQ.
Am I missing something?
Is this an F# limitation? If so, is it by desing? If not, will it be addressed in a future release?

If you're not yet using .NET 4.0, you can write that as:

#r "System.Threading"
open System.Linq

let someArray = [|"abc"; "def"|]

someArray.AsParallel<string>()
|> Seq.filter (fun s -> s.Length = 3)
|> Seq.length

Come .NET 4.0, you can just write:

let someArray = [|"abc"; "def"|]

someArray
|> Array.Parallel.filter (fun s -> s.Length = 3)
|> Array.length

F# prefers the use of the Seq module over Linq extension methods. There are some helper functions available, however, in the FSharp.PowerPack.Linq assembly.

If I remember correctly, getting PLINQ to work nicely with F# is on the to-do list of the development team at Microsoft, though I'm not sure it will appear in .NET 4.0. F# does however have Asynchronous Workflows , which is very similar to PLINQ (except it's based around list comprehensions instead, which is the standard functional way of doing things). I can't seem to find the article that mentions better support in F# for the Parallel Extensions (PLINQ/TPL), so don't quote me on it, but I'm pretty sure I saw it somewhere.

Apart from the MSDN page, this article seems like a good introduction to the topic.

There's also this blog series ( Using PLINQ in F# ) that might be handy to read if you prefer to use PLINQ over Async Workflows still.

扩展方法只是将对象作为第一个参数的静态,因此您应该可以使用它来调用它

ParallelEnumerable.AsParallel(someArray).Count(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM