Search code examples
c#f#c#-to-f#netmq

How to translate ReceiveReady method in NetMQ from C# to F#


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.


Solution

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