F#Discriminated Unions访问值

时间:2015-02-02 09:28:11

标签: f# discriminated-union

我有一个作为服务器运行的应用程序,进行一些计算并返回一个值。我创建了一个有区别的联合类型MessageType,因此我可以在应用程序之间传递不同类型的消息。

MessageTypeExchangeMessage类型ExchangeFrame组成。我的问题是如何从ExchangeFrame访问MessageType的值。

代码可能会更好地解释

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

1 个答案:

答案 0 :(得分:1)

如设计所示,您可以通过(1)模式匹配来访问交换帧,从MessageType中提取帧,然后(2)点到帧中以提取字段,如下所示:

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

但请看我对这个问题的评论。