0 people like it.

Weighted Average

Takes a list of (quantity/amount and price/rate) as decimals, and gives a weighted average

1: 
2: 
3: 
4: 
5: 
6: 
7: 
/// Takes a list of (quantity/amount and price/rate) as decimals, and gives a weighted average
let weightedAvg mylist =
    let weightedValue = mylist |> List.sumBy(fun (isum,irate) -> isum*irate)
    let weightedSum = mylist |> List.sumBy(fun (isum,irate) -> isum)
    match weightedSum with
    | 0m -> 0m
    | x -> weightedValue / x
val weightedAvg : mylist:(decimal * decimal) list -> decimal
 Takes a list of (quantity/amount and price/rate) as decimals, and gives a weighted average
val mylist : (decimal * decimal) list
val weightedValue : decimal
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
    interface IReadOnlyList<'T>
    interface IReadOnlyCollection<'T>
    interface IEnumerable
    interface IEnumerable<'T>
    member GetReverseIndex : rank:int * offset:int -> int
    member GetSlice : startIndex:int option * endIndex:int option -> 'T list
    static member Cons : head:'T * tail:'T list -> 'T list
    member Head : 'T
    member IsEmpty : bool
    member Item : index:int -> 'T with get
    ...
val sumBy : projection:('T -> 'U) -> list:'T list -> 'U (requires member ( + ) and member get_Zero)
val isum : decimal
val irate : decimal
val weightedSum : decimal
val x : decimal
Raw view Test code New version

More information

Link:http://fssnip.net/8aM
Posted:11 hours ago
Author:Tuomas Hietanen
Tags: average , seq average