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

查看:99
本文介绍了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所提到的,有一些内置的支持通用算术你可以使用'静态约束',它允许你自己定义一些泛型函数(尽管这有点有限)。

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 的数字操作(它实际上使用一些查找表,类型作为键)。然后,您可以使用数字操作对象的方法来执行诸如乘法,加法( Multiply Add )和许多其他。该功能适用​​于任何数字:

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# Matrix< YourType> Vector< YourType> 注册操作后。

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天全站免登陆