How do you work with IList<> in F#?
Asked Answered
H

4

5

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?

Holmquist answered 3/4, 2010 at 15:19 Comment(0)
B
7
efforts |> Seq.sumBy (fun e -> e.Amount)
Bangor answered 3/4, 2010 at 17:1 Comment(1)
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)"Holmquist
W
5

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.

Waterrepellent answered 3/4, 2010 at 18:14 Comment(0)
D
4
Seq.fold (fun acc (effort: Effort) -> acc + effort.Amount) 0.0 efforts
Debut answered 3/4, 2010 at 15:30 Comment(0)
P
4

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.

Partin answered 3/4, 2010 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.