So in doing some of the Project Euler problems, I want to be able to take the square root of integer values (int, long, bigint, etc), but Sqrt is only defined for floating-point values. So I’ve been writing my own little Newton-Raphson algorithm, and it’s plenty accurate for what I need. However, I want to be able to call the built-in sqrt function on floating-point values. So I wrote something like this:
let inline dsqrt x =
match box x with
| :? float -> sqrt x
| :? float32 -> sqrt x
| _ -> p_dsqrt x
My function, obviously, is named “p_dsqrt”. However, this function requires that the input have a Sqrt method defined, which sort of defeats the whole purpose. Am I missing some type constraint, or what?
I think you probably want this, instead:
The problem with your code is that you’re directly calling
sqrt x, which constrains the possible types ofx. In my modified code I bind a new identifier to the result of the successful coercion tofloatorfloat32, so this doesn’t put any constraint on the type ofx.