3
votes

I am working on some code where I need to use an f# query to sum a list.

For anyone who is working on f# basics, here's a handy link: https://learnxinyminutes.com/docs/fsharp/

So far, I have code that prints a statement for a sum of the square of 5 numbers.

So far, this correctly displays 3000 as the sum of the squares of each list. 'numbers' will be used for the query.

let square x = x * x
let numbers = [10.0; 20.0; 30.0; 40.0]

let sumOfSquare2 =
   [10.0; 20.0; 30.0; 40.0] 
   |> List.map square 
   |> List.sum 

printfn "Sum of square: %A" (sumOfSquare2)

let sumOfSquare = 
    List.sum ( List.map square [10.0; 20.0; 30.0; 40.0] )

printfn "Sum of square: %A" (sumOfSquare)

At the moment, I'm a little stuck on how to correctly use the 'square' function after the query.

// A query expression.

let query1 =
    query {
        for number in numbers do
            select (number)           
    }
   |> square query   


printfn "Query sum of squares: %A" (query1)

So how do I correctly present this? 'query' itself works (when using printfn on query) but when trying to pipeline the square function to query, it doesn't compile.

3

3 Answers

2
votes

It will be basically the same code you used with the list, but since the query returns a seq use Seq.map instead of List.map:

// A query expression.
let query1 =
    query {
        for number in numbers do
            select (number)           
    }
   |> Seq.map square    


printfn "Query sum of squares: %A" (query1)

Note that your query does not transform anything, but I think you did like this as an example.

1
votes

Kindly note that, the query returns a sequence which you can iterate and then do your operation

Ex:

// Print results of a query
query1
|> Seq.map (fun customer -> printfn "Company: %s Contact: %s" customer.CompanyName customer.ContactName)

You can use it like:

query1 |> Seq.map (fun e -> square(e)) |> Seq.sum

Full Source Code

open System

// your code goes here
let square x = x * x
let numbers = [10.0; 20.0; 30.0; 40.0]

let query1 =
    query {
        for number in numbers do
            select (number)           
    } |> Seq.map square |> Seq.sum

Console.WriteLine(sprintf "%A" query1);

Try it

To learn more about the query, please go to https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/query-expressions

1
votes

F# supports summing within the query, so you can just do this to get the sum of the squares:

query {
    for num in numbers do
    sumBy (square num)
}