F# 有通用算术支持吗? [英] Does F# have generic arithmetic support?

查看:21
本文介绍了F# 有通用算术支持吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

F# 是否与 C# 存在相同的问题,即不能直接使用具有泛型 T 类型的算术运算符?

Does F# have the same problem as C# where you can't directly use arithmetic operators with generic T types?

你能写一个通用的 Sum 函数来返回支持算术加法的任何值的总和吗?

Can you write a generic Sum function that would return the sum of any value that supports the arithmetic addition?

推荐答案

正如 brian 提到的,有一些对泛型算术的内置支持,你可以使用静态约束",它允许你自己定义一些泛型函数(尽管这有点有限).

As brian mentioned, there is some built-in support for generic arithmethic and you can use 'static constraints' which allow you to define some generic functions yourself (although this is a bit limited).

除此之外,您还可以使用动态数字关联",这在函数中使用时会慢一点,但它可以很好地用于例如定义您自己的向量或矩阵类型.下面是一个例子:

In addition to this, you can also use dynamic 'numeric associations', which is a bit slower when using in a function, but it can be nicely used for example to define your own vector or matrix type. Here is an example:

#r "FSharp.PowerPack.dll"
open Microsoft.FSharp.Math

let twoTimesLarger (n:'a) (m:'a) = 
  let ops = GlobalAssociations.GetNumericAssociation<'a>()
  let sel = if ops.Compare(n, m) > 0 then n else m
  ops.Multiply(sel, ops.Add(ops.One, ops.One))

我们首先需要引用包含该功能的 F# PowerPack 库.然后我们定义一个带有签名的泛型函数 'a ->'a ->'一个.第一行动态获取用于处理 'a 类型的数字操作(它本质上使用一些以该类型为键的查找表).然后,您可以使用数值运算对象的方法来执行乘法、加法(MultiplyAdd)等操作.该函数适用于任何数字:

We first need to reference F# PowerPack library which contains the functionality. Then we define a generic function with a signature 'a -> 'a -> 'a. The first line dynamically gets numeric operations for working with the type 'a (it essentially uses some lookup table with the type as the key). Then you can use methods of the numeric operations object to perform things like multiplication, addition (Multiply, Add) and many others. The function works with any numbers:

twoTimesLarger 3 4  
twoTimesLarger 2.3 2.4
twoTimesLarger "a" "b" // Throws an exception!

当您定义自己的数字类型时,您可以定义其数字操作并使用 GlobalAssociations.RegisterNumericAssociation 注册它们.我相信这也意味着您将能够在注册操作后使用内置的 F# MatrixVector.

When you define your own numeric type, you can define its numeric operations and register them using GlobalAssociations.RegisterNumericAssociation. I believe this also means that you'll be able to use built-in F# Matrix<YourType> and Vector<YourType> after registering the operations.

这篇关于F# 有通用算术支持吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆