Alan Mulligan
Alan Mulligan

Reputation: 1198

F# Discriminated Unions access values

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 ()

Upvotes: 0

Views: 429

Answers (1)

Grundoon
Grundoon

Reputation: 2764

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.

Upvotes: 1

Related Questions