If I have a C# class with implicit conversion to double, like so:
public class Parameter
{
private double _value;
FSharp.Interop.Dynamic uses the DLR, so for most people probably overkill, but has a function Dyn.implicitConvert
for dynamically using the C# implicit operator.
[<Test>] member basic.``Test Implicit Conversion`` ()=
let ele = 50
ele |> Dyn.implicitConvert |> should equal (decimal 50)
It won't let you do implicit conversions. Make your conversions explicit where you need to.
See here for various ways to do it explicitly: http://natehoellein.blogspot.com/2008/02/basic-type-conversions-with-f.html
F# does not perform implicit conversions, but it allows you to define an explicit operator to run them. See the kvb's answer to a previous question:
let inline (!>) (x:^a) : ^b = ((^a or ^b) : (static member op_Implicit : ^a -> ^b) x)
This is using statically resolved type parameters to say that either the input or the result needs to provide implicit conversion operator - these are compiled to methods named op_Implicit
, so the F# compiler checks for a static method with this special name.
Using the !>
operator, you can now explicitly say where you want to convert Parameter
to a float
(two times) in your code sample like this:
let a = Parameter(4.0)
let b = Parameter(2.0)
let c = !> a * Math.Sin(!> b)
I think the main reason for not allowing implicit conversions in F# is that it would make the type inference a bit more difficult and it would be hard for the compiler to give good error messages.