Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic zero for generic function

Tags:

inline

f#

I have a function to calculate the cumulated sum of a sequence.

let cumsum<'T> = Seq.scan (+) 0 >> Seq.skip 1 >> Seq.toArray

Though it looks generic, the integer 0 makes it non-generic, and thus I cannot call the function with a sequence of floats.

Is there a generic zero that can replace my hardcoded 0, or maybe a different way of making the function generic.

like image 846
kasperhj Avatar asked Jan 21 '15 09:01

kasperhj


2 Answers

You can use the GenericZero primitive but you need to make your function inline and make it explicitly a function (right now your function is written in point-free style) since in principle values cannot be made inline.

let inline cumsum s = 
  s |> Seq.scan (+) LanguagePrimitives.GenericZero |> Seq.skip 1 |> Seq.toArray

Note that by removing the Type parameter 'T the static member constraints are inferred automatically by the compiler:

val inline cumsum :
  s:seq< ^a> ->  ^b []
    when ( ^b or  ^a) : (static member ( + ) :  ^b *  ^a ->  ^b) and
          ^b : (static member get_Zero : ->  ^b)
like image 146
Gus Avatar answered Nov 05 '22 05:11

Gus


 LanguagePrimitives.GenericZero

:)

like image 29
rkrahl Avatar answered Nov 05 '22 05:11

rkrahl