英文:
In F#, converting int option to Google.Protobuf Int32Value
问题
有没有一种更高效的方式在将整数选项类型转换为 Google.Protobuf.FSharp.WellKnownTypes.Int32Value 后再将其序列化到网络上?下面的代码可以工作,但感觉有点笨拙:
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
英文:
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
答案1
得分: 2
请你再确认一下你的代码片段是否确实有效?我对此有点困惑,因为你似乎是在创建 Int32Value
时,将 Value
设置为可选值,而不是一个 int32
值,这对我来说看起来不正确。
话虽如此,我认为最优雅的选项是首先将 option
转换为 ValueOption
,然后在内部将值从 int
转换为 Int32Value
。
我没有看到内置的转换函数,所以你可能需要定义自己的:
module ValueOption =
let ofOption = function Some v -> ValueSome v | None -> ValueNone
在此基础上(并假设我正确理解了 Int32Value
),你应该能够编写类似这样的代码:
let f (x:int option) : ValueOption<Google.Protobuf.FSharp.WellKnownTypes.Int32Value> =
x
|> ValueOption.ofOption
|> ValueOption.map (fun n -> { Int32Value.empty() with Value = n })
或者如果你更喜欢函数组合而不是管道操作(我不是,但很多人喜欢):
let f =
ValueOption.ofOption >>
ValueOption.map (fun n -> { Int32Value.empty() with Value = n })
英文:
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 })
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论