Generic zero for generic function

旧城冷巷雨未停 提交于 2019-12-23 09:59:53

问题


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.


回答1:


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)



回答2:


 LanguagePrimitives.GenericZero

:)



来源:https://stackoverflow.com/questions/28064129/generic-zero-for-generic-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!