F# – defining explicit operator in F#

Update 2012/08/23: Thanks for the suggestion from Jizugu in the comments, I’ve updated the post to show you his approach to calling the explicit operator in a clean and elegant way.

 

In C#, you can define an explicit operator for your type using the explicit keyword:

image

You can define an explicit operator like the below and use a custom operator to make invoking the explicit operator in an elegant way rather than having to call the static Person.op_Explicit method:

  • http://keithsheppard.name Keith

    Hi, It seems that (Person “Yan Cui”) just calls the Person constructor and so the explicit op is never exercised in this example. I added a print to your code to check this https://gist.github.com/3324408

    Do you know if there is some way to invoke op_Explicit in F# other than (Person.op_Explicit “Yan Cui”)? I tried (“yan Cui” :> Person) but the compiler doesn’t like that.

    Best, Keith

  • theburningmonk

    Hi Keith, thank you very much for pointing that out! I’ve reworked the example, but haven’t found a way to invoke op_Explicit beyond Person.op_Explicit, if you happen to stumble across a way to do it then please do let me know!

  • Andrew

    When were these introduced? They kinda remind me of Scala’s
    object Person { def apply(name: String) = new Person(name) }
    …but slightly uglier. Still, these could come in handy, thanks for posting!

  • Jizugu

    One option…

    let inline (!>) (b:^b) : ^a = (^a : (static member op_Explicit: ^b -> ^a)(b))

    then do

    let person:Person = !>”Yan Cui”
    OR
    let person = !>”Yan Cui”:Person

  • theburningmonk

    @Jizugu – very nice!