Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are LINQ expressions an acceptable way to manipulate data in F#?

I'm a beginner F# programmer. I know that F# is functional, and prefers a style where data is piped through functions, such as map and iter functions on collections. Still, LINQ expressions offer an alternative, highly readable method for manipulating collections; however, I'm unsure if it is more imperative and defeats the point of using a functional language.

For example, without LINQ:

let listOfPrimes n =
    [1UL..n]
    |> List.choose (fun i -> match i with
                             | i when isPrime i -> Some i
                             | _ -> None)

While with LINQ, we can do:

let listOfPrimes n =
    query {
        for i in [1UL..n] do
        where (isPrime i)
        select i
    }
    |> List.ofSeq

I note that we need to transform the resultant sequence to a list when using LINQ. So, what's the practical performance difference? Is LINQ stylistically frowned upon outside of actual database queries? When is it appropriate to manipulate collection data using queries outside of that scenario?

like image 860
Nerve Avatar asked Oct 17 '25 16:10

Nerve


1 Answers

I think it is a matter of preference - some people prefer to write code using higher-order functions, some people prefer LINQ-style query expressions.

It is worth noting, that there are also sequence expressions, which can be seen as simpler version of the query syntax. Sequence expressions do not give you easy access to the additional query operators, but they work nicely for simple things and you can also use the [ ... ] notation to get the result as lists:

let listOfPrimes n =
  [ for i in [1UL..n] do
      if (isPrime i) then yield i ]

My personal preference is:

  • Use sequence expressions for simple filtering & projection & choosing
  • Use higher-order functions for other operations (perhaps with the exception of complex grouping and joining where query expressions are nicer).
  • Use query expressions for database access
like image 86
Tomas Petricek Avatar answered Oct 20 '25 17:10

Tomas Petricek