【问题标题】:How can I use Seq.sum for any .Net value types?如何将 Seq.sum 用于任何 .Net 值类型?
【发布时间】:2015-06-26 19:25:00
【问题描述】:

我正在寻找一个函数来处理任何数字类型数据(int、float、double)的序列,通过映射对其进行一些计算,然后对这些计算值进行求和。我遇到的问题是 Seq.sum (或者实际上只是'(+)')导致类型参数为整数,或者只是给出一个完全错误的错误。似乎应该有一种方法可以通过使用类型约束来完成这项工作,但我似乎无法得到它。

type ValueWithComputation<'v> = {Value: seq<'v>; Computation: 'v -> 'v}

let calculateAndCombine (x: ValueWithComputation<'v>) = 
    x.Value
    |> Seq.map x.Computation
    |> Seq.sum // sometimes gives error: "Could not resolve the ambiguity inherent in the use of operator '(+)'

let x = {Value= {1..10}; Computation= (fun x->x*2)}
let y = {Value= {(1.0)..(10.0)}; Computation= (fun x->x*x)}

let totalX = calculateAndCombine x //this causes the code force 'v to be int
let totalY = calculateAndCombine y //gives an error since this isn't an int

这似乎类似于F# generics / function overloading syntax,但它并没有真正解释如何让它适用于所有值类型。

【问题讨论】:

标签: f# type-parameter


【解决方案1】:

我让它像这样工作。阅读 Foggy Finder 链接的答案。然后,您还需要静态成员 Zero 才能使 sum 工作。

type ValueWithComputation< ^T when ^T: (static member (+): ^T * ^T -> ^T) and ^T: (static member Zero: ^T)> = 
  { Value: seq< ^T>
    Computation: ^T -> ^T }

let inline calculateAndCombine x = 
    x.Value
    |> Seq.map x.Computation
    |> Seq.sum

let x = {Value= {1..10}; Computation= (fun x->x*2)}
let y = {Value= {(1.0)..(10.0)}; Computation= (fun x->x*x)}

let totalX = calculateAndCombine x
let totalY = calculateAndCombine y

【讨论】:

  • 这是有道理的。我没有意识到您可以限制该类型具有哪些成员。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2010-10-17
相关资源
最近更新 更多