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 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  3. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

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 *