Update 2012/08/23: Thanks for the sug­ges­tion from Jizugu in the com­ments, I’ve updated the post to show you his approach to call­ing the explicit oper­a­tor in a clean and ele­gant way.

 

In C#, you can define an explicit oper­a­tor for your type using the explicit keyword:

image

You can define an explicit oper­a­tor like the below and use a cus­tom oper­a­tor to make invok­ing the explicit oper­a­tor in an ele­gant way rather than hav­ing to call the sta­tic Person.op_Explicit method:

Share

5 Responses to “F# – defining explicit operator in F#”

  1. Keith says:

    Hi, It seems that (Per­son “Yan Cui”) just calls the Per­son con­struc­tor and so the explicit op is never exer­cised in this exam­ple. 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” :> Per­son) but the com­piler doesn’t like that.

    Best, Keith

  2. theburningmonk says:

    Hi Keith, thank you very much for point­ing that out! I’ve reworked the exam­ple, but haven’t found a way to invoke op_Explicit beyond Person.op_Explicit, if you hap­pen to stum­ble across a way to do it then please do let me know!

  3. Andrew says:

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

  4. Jizugu says:

    One option…

    let inline (!>) (b:^b) : ^a = (^a : (sta­tic mem­ber op_Explicit: ^b -> ^a)(b))

    then do

    let person:Person = !>“Yan Cui“
    OR
    let per­son = !>“Yan Cui”:Person

  5. theburningmonk says:

    @Jizugu — very nice!

Leave a Reply