20

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

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742

4 Answers4

22

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

type Bar() =
    interface IFoo with
        member this.Bar () = ()
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
  • @Drew - It is an awesome language. – ChaosPandion Jun 18 '10 at 13:30
  • 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 Jun 18 '10 at 17:18
  • @Jason - Thanks, it is safe to assume that @Drew implicitly corrected my mistake. – ChaosPandion Jun 18 '10 at 17:30
  • @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 Jun 18 '10 at 18:19
  • @Drew - Wait your method wasn't named Bar? That is a production quality method name... :) – ChaosPandion Jun 19 '10 at 16:16
7

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.

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
Brian
  • 117,631
  • 17
  • 236
  • 300
6

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

corvuscorax
  • 5,850
  • 3
  • 30
  • 31
  • 7
    To be pedantic, the return _type_ is `unit`, the only _value_ of that type is spelled `()`. – Brian Jun 18 '10 at 08:58
3

The equivalent in F# is:

type IFoo =
    abstract member Bar: unit -> unit
Márcio Azevedo
  • 123
  • 1
  • 4
  • 8