使函数适用于所有数字类型(int、float、long) [英] make function work with all numeric types (int, float, long)

查看:22
本文介绍了使函数适用于所有数字类型(int、float、long)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个简单的函数:

let sum a b = a + b

仅适用于 int 类型

如何使它也适用于 float 和 long ?

how to make it so that it would also work for float and long ?

推荐答案

使用 内联:

let inline sum a b = a + b

<小时>

更新:

如果您有兴趣编写自己的多态数值函数,您应该同时使用 inlineLanguagePrimitives 模块.

If you're interested in writing your own polymorphic numerical functions, you should use both inline and LanguagePrimitives module.

这是来自线程的多态余弦函数 Converting Haskell Polymorphic Cosine function toF#:

Here is a polymorphic cosine function from the thread Converting Haskell Polymorphic Cosine function to F#:

let inline cosine n (x: ^a) = 
    let one: ^a = LanguagePrimitives.GenericOne
    Seq.initInfinite(fun i -> LanguagePrimitives.DivideByInt (- x*x) ((2*i+1)*(2*i+2)))
    |> Seq.scan (*) one
    |> Seq.take n
    |> Seq.sum

这篇关于使函数适用于所有数字类型(int、float、long)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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