作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以在做一些Project Euler问题,我希望能够取整数值(int、long、bigint 等)的平方根,但 Sqrt 仅针对浮点值定义。所以我一直在写我自己的小 Newton-Raphson 算法,它非常准确,可以满足我的需要。但是,我希望能够对浮点值调用内置的 sqrt 函数。所以我写了这样的东西:
let inline dsqrt x =
match box x with
| :? float -> sqrt x
| :? float32 -> sqrt x
| _ -> p_dsqrt x
最佳答案
如果要使用匹配,则不需要 inline 关键字,但如果要使用内联函数和“帽子类型”,请使用重载而不是匹配:
type Sqrt = Sqrt with
// Dummy overload in order to get the right types inferred (will never reach here)
static member inline ($) (Sqrt, _:^t when ^t:null and ^t: struct) = id
// Existing sqrt
static member inline ($) (Sqrt, x:'a) :'a = sqrt x
// Your Newton-Raphson based sqrt's
static member ($) (Sqrt, x:int ) = sqrtForInt x
static member ($) (Sqrt, x:bigint) = sqrtForBigInt x
let inline sqrt (x:'t) :'t = Sqrt $ x
关于F# 过于激进的类型推断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12572471/
我是一名优秀的程序员,十分优秀!