Search code examples
f#protocol-buffers

In F#, converting int option to Google.Protobuf Int32Value


Is there a more efficient way to convert an integer option type to Google.Protobuf.FSharp.WellKnownTypes.Int32Value before serializing it across a network? The code below works but feels awkward:

let f (x:int option) : ValueOption<Google.Protobuf.FSharp.WellKnownTypes.Int32Value> = 
    let bb = match x with
        | None -> ValueNone
        | Some xx -> ValueSome xx
    let c = {Int32Value.empty() with Value = bb }
    match c.Value with
    |ValueNone -> ValueNone
    |ValueSome s ->ValueSome c

TIA


Solution

  • Could you double-check that your snippet actually works? I'm a bit confused by that, because you seem to be creating Int32Value with Value set to an optional value - rather than an int32 value - and that does not look right to me.

    That said, I think the most elegant option is to first turn option into ValueOption and then transform the value inside from int to Int32Value.

    I do not see a built-in conversion function, so you may need to define your own:

    module ValueOption = 
      let ofOption = function Some v -> ValueSome v | None -> ValueNone
    

    Given this (and assuming I correctly understand Int32Value), you should be able to write something like:

    let f (x:int option) : ValueOption<Google.Protobuf.FSharp.WellKnownTypes.Int32Value> = 
      x 
      |> ValueOption.ofOption
      |> ValueOption.map (fun n -> { Int32Value.empty() with Value = n })
    

    Or if you prefer function composition over pipes (I do not, but many do):

    let f =
      ValueOption.ofOption >>
      ValueOption.map (fun n -> { Int32Value.empty() with Value = n })