views:

219

answers:

3

Imagine the following interface in C#:

interface IFoo {
    void Bar();
}

How can I implement this in F#? All the examples I've found during 30 minutes of searching online show only examples that have return types which I suppose is more common in a functional style, but something I can't avoid in this instance.

Here's what I have so far:

type Bar() =
    interface IFoo with
        member this.Bar() =
            void

Fails with FS0010: Unexpected keyword 'void' in expression.

+9  A: 

The equivalent is unit which is syntactically defined as ().

type Bar() =
    interface IFoo with
        member this.Bar () = ()
ChaosPandion
Thanks. I'm enjoying learning F#!
Drew Noakes
@Drew - It is an awesome language.
ChaosPandion
The C# code was a method, not a property. To reproduce this in F#, I believe you need a member with signature unit -> unit. This would be written "member this.Bar () = ()". Without the unit parameter, the F# could would be a property with a getter.
Jason
@Jason - Thanks, it is safe to assume that @Drew implicitly corrected my mistake.
ChaosPandion
@Jason, you're right. Actually my method took arguments (and surprisingly wasn't called Bar!) so I'd messed up transcribing it in the original question. Thanks for pointing this out. I'll edit the question.
Drew Noakes
@Drew - Wait your method wasn't named Bar? That is a production quality method name... :)
ChaosPandion
+3  A: 

The return type needs to be (), so something like member this.Bar = () should do the trick

corvuscorax
To be pedantic, the return _type_ is `unit`, the only _value_ of that type is spelled `()`.
Brian
+4  A: 

For general info on F# types, see

The basic syntax of F# - types

From that page:

The unit type has only one value, written "()". It is a little bit like "void", in the sense that if you have a function that you only call for side-effects (e.g. printf), such a function will have a return type of "unit". Every function takes an argument and returns a result, so you use "unit" to signify that the argument/result is uninteresting/meaningless.

Brian
Thanks for the link. I included a quote from the page in your answer.
Drew Noakes