F# – defining explicit operator in F#

Yan Cui

I help clients go faster for less using serverless technologies.

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:


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


5 thoughts on “F# – defining explicit operator in F#”

  1. 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

  2. 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!

  3. 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!

  4. 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

Leave a Comment

Your email address will not be published. Required fields are marked *