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

查看:91
本文介绍了使函数适用于所有数值类型(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


更新:

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

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

这里是线程将Haskell多态余弦函数转换为多态余弦函数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天全站免登陆