Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Extension methods are just statics that take the object as the first parameter, so you should be able to call it with

ParallelEnumerable.AsParallel(someArray).Count(...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top