1

I'm working with a library that does not have F# documentation, only C#. Having no familiarity with C# I'm having a bit of trouble. Reading through the documentation for NetMQ, there is one line that I'm having trouble translating:

For context, here is the full example:

using (var rep1 = new ResponseSocket("@tcp://*:5001"))
using (var rep2 = new ResponseSocket("@tcp://*:5002"))
using (var poller = new NetMQPoller { rep1, rep2 })
{
    rep1.ReceiveReady += (s, a) =>    // ??????
    {
        string msg = a.Socket.ReceiveString();
        a.Socket.Send("Response");
    };
    rep2.ReceiveReady += (s, a) =>    // ??????
    {
        string msg = a.Socket.ReceiveString();
        a.Socket.Send("Response");
    };

    poller.Run();
}

Specifically, I don't know what rep1.ReceiveReady += (s, a) => means in the context of C# as well as how to translate it to F#. Any ideas? Thanks.

  • Please see my answer here: http://stackoverflow.com/a/34161972/3932049 for information on the => operator – Camilo Terevinto Jul 30 '16 at 23:58
  • 2
    @CamiloTerevinto : This has nothing to do with expression-bodied members though, this is just a lambda... – ildjarn Jul 31 '16 at 00:37
  • 2
    I'm the author of NetMQ, happy that you are using NetMQ and found an answer. You can contribute to the project with adding F# docs or some example. – somdoron Jul 31 '16 at 05:39
  • 1
    Its a great library. Actually in some cases the NetMQ docs provide a better explanation of some concepts than the Zguide. I very well might contribute some F# examples in the future. Thanks for the great work. – professor bigglesworth Jul 31 '16 at 13:50

1 Answers1

4

rep.ReceiveReady += (s, a) => { /*...*/ }; is subscribing to the ReceiveReady event with a lambda function. Here is a direct F# translation:

use rep1 = new ResponseSocket("@tcp://*:5001")
use rep2 = new ResponseSocket("@tcp://*:5002")

use poller = new NetMQPoller()
poller.Add rep1
poller.Add rep2

rep1.ReceiveReady.Add (fun a -> let msg = a.Socket.ReceiveString ()
                                a.Socket.Send "Response")
rep2.ReceiveReady.Add (fun a -> let msg = a.Socket.ReceiveString ()
                                a.Socket.Send "Response")

poller.Run ()

Further reading on event handling in F# can be found in the documentation. Note, however, that F# can also treat events as observables, which is likely to be considered more idiomatic.

ildjarn
  • 62,044
  • 9
  • 127
  • 211