2 people like it.

Seq.sumBy implemented in terms of Seq.fold

Seq.sumBy implemented in terms of Seq.fold

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
let inline mySumBy (projection : ^T -> ^U) (source : seq< ^T >) : ^U =
    (LanguagePrimitives.GenericZero< ^U >, source)
    ||> Seq.fold (fun acc value -> value |> projection |> Checked.(+) acc)

do
    let l = [ 1, 11.; 2, 22.; 3, 33.; 4, 44. ]
    let ints = mySumBy fst l
    let floats = mySumBy snd l
    printfn "ints: %d, floats: %f" ints floats
val mySumBy : projection:('T -> 'U) -> source:seq<'T> -> 'U (requires member get_Zero and member ( + ))

Full name: Script.mySumBy
val projection : ('T -> 'U) (requires member get_Zero and member ( + ))
val source : seq<'T>
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
module LanguagePrimitives

from Microsoft.FSharp.Core
val GenericZero<'T (requires member get_Zero)> : 'T (requires member get_Zero)

Full name: Microsoft.FSharp.Core.LanguagePrimitives.GenericZero
module Seq

from Microsoft.FSharp.Collections
val fold : folder:('State -> 'T -> 'State) -> state:'State -> source:seq<'T> -> 'State

Full name: Microsoft.FSharp.Collections.Seq.fold
val acc : 'U (requires member get_Zero and member ( + ))
val value : 'T
module Checked

from Microsoft.FSharp.Core.Operators
val l : (int * float) list
val ints : int
val fst : tuple:('T1 * 'T2) -> 'T1

Full name: Microsoft.FSharp.Core.Operators.fst
val floats : float
val snd : tuple:('T1 * 'T2) -> 'T2

Full name: Microsoft.FSharp.Core.Operators.snd
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Raw view Test code New version

More information

Link:http://fssnip.net/5U
Posted:12 years ago
Author:ildjarn
Tags: sumby , fold