How to sum a participant by seq <type>?

Can someone help me afloat here? Still new to F #, actually trying for the first time to use it for something serious, but nOOb is stuck in this problem.

I have type Asset

type Asset(line:string) = let fields = line.Split(',') member this.EAD = Double.Parse(fields.[8]) 

Then I expose the csv file as seq <Asset>:
"data" here are seq <string> lines in the file

 let assets = Seq.map(fun line -> Asset(line)) data 

Now I want to get the total EAD of these assets, but I get an error

 'This value is not a function and cannot be applied'. 

Here are some of the things I've tried:

 let totEAD = Seq.sum(a.EAD) assets // first try let totEAD = Seq.sum(fun(a)->a.EAD) assets // pretty sure this is a function.. let getEad(a:Asset) = a.EAD // val getEad : Asset -> float ... is it a val of a function? let x = Seq.sum(fun (a) -> getEad(a)) assets // nope... 

Thanks in advance,

Geert Yang

update:

It works, but I'm still puzzled, why can't I do it at a time, any tips there?

 let x = Seq.map(fun (a:Asset) -> a.EAD) assets // first turn it into a seq<float> let tot = Seq.sum(x) 
+4
source share
1 answer

Your problem is that Seq.sum assumes that it is able to work on the whole type and does not accept lambda. He is looking for an operator (+) to determine your type. What you want to do is use sumBy, which accepts lambda.

Also, prefer piping syntax. If you first specify the input sequence, then the smart type output system can then work in sumby lambda, which type you are dealing with automatically, so you do not need to add type annotations:

 let total = assets |> Seq.sumBy( fun a -> a.EAD ) 
+16
source

Source: https://habr.com/ru/post/1337114/


All Articles