0

I have a application which runs as a server, dose some calculations and returns a value. I have created a discriminated union type of MessageType so I can have different types of messages passed between applications.

The MessageType is made up of an ExchangeMessage of type ExchangeFrame. The question I have is how to access the values of ExchangeFrame from the MessageType.

The code might explain it better

[<CLIMutable>]
type ExchangeFrame = 
    { 
    FrameType: FrameType
    Amount: double;
    ConvertTo: Currency
    ConvertFrom: Currency 
    }

type MessageType = ExchangeMessage of ExchangeFrame

let server () = 
    use context = new Context()

    // socket to talk to clients
    use responder = context |> Context.rep
    "tcp://*:5555" |> Socket.bind responder

    Console.WriteLine("Server Running")

    while true do
        // wait for next request from client
        let messageReceived = responder |> Socket.recv |> decode |> deserializeJson<MessageType> 

        //Do Calculations
        let total = doCalculations //MessageReceived.ExchangeMessage.Amount 3.0 

        // send reply back to client
        let message = encode <| total
        message |> Socket.send responder

server ()
ildjarn
  • 59,718
  • 8
  • 115
  • 201
Alan Mulligan
  • 937
  • 2
  • 13
  • 32
  • 1
    Dont you just want `match somevar with |ExchangeMessage(frame) -> .. //do something with frame` – John Palmer Feb 02 '15 at 09:40
  • Thanks John, but I am still a little confused on how I can access each value in my exchangeframe. can you elaborate a little please – Alan Mulligan Feb 02 '15 at 10:43
  • 1
    Then you can just do `frame.Amount` or whatever – John Palmer Feb 02 '15 at 11:00
  • Comment on naming: for single case DUs, it's standard to have the case be named after the type like this `type MessageType = MessageType of ExchangeFrame` or `type ExchangeMessage = ExchangeMessage of ExchangeFrame` – Grundoon Feb 02 '15 at 12:55
  • 1
    It's not clear to me why the extra `MessageType` wrapper is needed at all. Why not use the `ExchangeFrame` directly? – Grundoon Feb 02 '15 at 12:55

1 Answers1

1

As the design stands, you can access the exchange frame by (1) pattern matching to extract the frame from the MessageType, and then (2) dotting into the frame to extract a field, like this:

let msgType = // creation
let (ExchangeMessage frame) = msgType
let amount = frame.Amount

But see my comments to the question.

Grundoon
  • 2,644
  • 1
  • 16
  • 21