Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define explicit operator in F#?

Tags:

f#

c#-to-f#

How do you implement the equivalent of C#'s explicit operator in F#? Is it supported?

like image 667
theburningmonk Avatar asked Aug 10 '12 00:08

theburningmonk


People also ask

What is an implicit operator?

The Implicit Operator According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to your C# class, which can accepts any reasonably convertible data type without type casting.

What is implicit using in C#?

Implicit conversion is the conversion in which a derived class is converted into a base class like int into a float type. Explicit conversion is the conversion that may cause data loss. Explicit conversion converts the base class into the derived class.

Which operator can be used to convert in C#?

Use the operator and implicit or explicit keywords to define an implicit or explicit conversion, respectively. The type that defines a conversion must be either a source type or a target type of that conversion. A conversion between two user-defined types can be defined in either of the two types.


1 Answers

Just implement an op_Explicit static member like

type SomeType() =
    static member op_Explicit(source: SomeType) : int =
        1

and then you can use a corresponding F# explicit conversion operator like

SomeType() |> int

you can see a bit into how this works by noting the static member constraint on the type signature of int

^a -> int when  ^a : (static member op_Explicit :  ^a -> int)
like image 52
Stephen Swensen Avatar answered Feb 07 '23 05:02

Stephen Swensen