Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to creating a C# implicit operator in F#?

Tags:

c#

f#

In C# I can add implicit operators to a class as follows:

public class MyClass {     private int data;      public static implicit operator MyClass(int i)     {         return new MyClass { data = i };     }      public static implicit operator MyClass(string s)     {         int result;          if (int.TryParse(s, out result))         {             return new MyClass { data = result };         }         else         {             return new MyClass { data = 999 };         }     }      public override string ToString()     {         return data.ToString();     } } 

Then I can pass any function that is expecting a MyClass object a string or an int. eg

public static string Get(MyClass c) {     return c.ToString(); }  static void Main(string[] args) {     string s1 = Get(21);     string s2 = Get("hello");     string s3 = Get("23"); } 

Is there a way of doing this in F#?

like image 203
wethercotes Avatar asked Nov 06 '09 11:11

wethercotes


People also ask

Is AC the same as AC?

In the air conditioning industry, the term HVAC is often used instead of AC. HVAC refers to heating, ventilation, and air conditioning, whereas AC simply refers to air conditioning. AC is generally used when referring to systems that are designed to cool the air in your home.


2 Answers

As others have pointed out, there is no way to do implicit conversion in F#. However, you could always create your own operator to make it a bit easier to explicitly convert things (and to reuse any op_Implicit definitions that existing classes have defined):

let inline (!>) (x:^a) : ^b = ((^a or ^b) : (static member op_Implicit : ^a -> ^b) x) 

Then you can use it like this:

type A() = class end type B() = static member op_Implicit(a:A) = B()  let myfn (b : B) = "result"  (* apply the implicit conversion to an A using our operator, then call the function *) myfn (!> A()) 
like image 192
kvb Avatar answered Sep 23 '22 06:09

kvb


Implicit conversion is rather problematic with respect to type safety and type inference, so the answer is: No, it actually would be a problematic feature.

like image 24
Francesco Avatar answered Sep 20 '22 06:09

Francesco