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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With