Search code examples
linqvisual-studio-2010f#extension-methodsplinq

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?


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.