Question

I have a list of type IList<Effort>. The model Effort contains a float called Amount. I would like to return the sum of Amount for the whole list, in F#. How would this be achieved?

Was it helpful?

Solution

efforts |> Seq.sumBy (fun e -> e.Amount)

OTHER TIPS

Upvoted the answers of Seq.fold, pipelined Seq.fold, and pipelined Seq.sumBy (I like the third one best).

That said, no one has mentioned that seq<'T> is F#'s name for IEnumerable<T>, and so the Seq module functions work on any IEnumerable, including ILists.

Seq.fold (fun acc (effort: Effort) -> acc + effort.Amount) 0.0 efforts

One detail that may be interesting is that you can also avoid using type annotations. In the code by sepp2k, you need to specify that the effort value has a type Effort, because the compiler is processing code from the left to the right (and it would fail on the call effort.Amount if it didn't know the type). You can write this using pipelining operator:

efforts |> Seq.fold (fun acc effort -> acc + effort.Amount) 0.0  

Now, the compiler knows the type of effort because it knows that it is processing a collection efforts of type IList<Effort>. It's a minor improvement, but I think it's quite nice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top