tags:

views:

120

answers:

4

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?

+4  A: 
Seq.fold (fun acc (effort: Effort) -> acc + effort.Amount) 0.0 efforts
sepp2k
+1, but should be `0.0` instead of `0`
kvb
+3  A: 

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.

Tomas Petricek
+4  A: 
efforts |> Seq.sumBy (fun e -> e.Amount)
Mauricio Scheffer
Soon after asking the question, I remembered that I should be using Seq instead of List and came to the same conclusion as yours. "member x.TotalEffort = x.Effort |> Seq.sumBy(fun i -> i.Amount)"
kim3er
+4  A: 

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.

Brian