generics - F# extending constrained array
问题描述
Say I have the following snippet
type 'T``[]`` when 'T : (static member (+) : 'T -> 'T -> 'T) with
member inline self.sum = Array.fold ( + ) self
It's hopefully obvious that I want to add an extension method only when 'T supports the +
operator.
However, I keep getting the following errors:
Error FS0957 One or more of the declared type parameters for this type extension have a missing or wrong type constraint not matching the original type constraints on '[]<_>'
Is this specific of an extension method possible? If it is, what am I missing?
解决方案
我能想到的最好的办法是
type 'T``[]`` with
member inline this.mysum< ^T when ^T : (static member (+) : ^T * ^T -> ^T)>() =
Array.reduce (fun v1 v2 -> (^T : (static member (+): ^T * ^T -> ^T) (v1, v2)))
这仍然不起作用(至少在 FSI 中 - 没有尝试编译)。我不确定这是否可能。
相反,我建议您使用以下IEnumerable<_>
扩展方法System.Linq
:
open System.Linq
[| 1..10 |].Sum()
推荐阅读
- sql - oracle中的数据排序
- azure - Application Insights 显示在实时指标中,但不在日志分析中
- java - 如何在日历中实现此日期格式
- mysql - 使用 MySQL 构建数据透视表(已编辑)
- machine-learning - 训练了一个复杂的自动编码器。现在需要帮助提取特征空间
- spring-boot - 如何将我的 Spring Boot 应用程序连接到 Docker 上的 Redis 容器?
- python - 为什么在导入 Zipline 时出现模块错误?
- flutter - 将位置流从 Geolocator 获取到 StreamBuilder Flutter
- typescript - 如何在打字稿的构造函数中编写异步函数
- node.js - 如何使用nodeJS + multer + sequelize存储pdf文件