F#中的Int选项而不是Int# [英] Int Option instead of Int in F#
问题描述
我遇到以下问题:
let safeDiv x y =
match (x,y) with
| (_, Some 0) -> None
| (Some xx, Some yy) -> Some (xx/yy)
| _ -> None
当我在Visual Studio的交互式窗口中运行这个简单的函数时,如下所示:
When I go to run this simple function in the interactive window of Visual Studio like so:
safeDiv 4 2
我收到以下错误...
I get the following error...
此表达式应该具有int类型选项,但此处的类型为int。
This expression was expected to have type int option but here has type int.
可能是我打算使用 safeDiv
一些(4)
一些(2)
?这不起作用......
Could it be I'm meant to use safeDiv
Some(4)
Some(2)
? This doesn't work either...
推荐答案
好的,这太过分了,但我最近做了类似的事情。
Ok, this is overkill but I actually did something similar to this recently.
首先,我为选项类型定义了一个计算表达式构建器:
First I defined a computation expression builder for the option type:
type OptionBuilder() =
member this.Bind(x, f) = Option.bind f x
member this.Return(x) = Some x
member this.ReturnFrom(x) = x
let opt = new OptionBuilder()
然后我定义了一个函数float类型的sub - > float - > float选项
And then I defined a function sub of type float -> float -> float option
let sub x y = if y = 0.0 then None else Some (x / y)
最后我使用OptionBuilder将saveDiv定义为float选项 - > float选项 - > float选项
And finally I used the OptionBuilder to define saveDiv as float option -> float option -> float option
let safeDiv x y = opt { let! a = x
let! b = y
return! sub a b }
您可以在wikibooks上阅读有关计算表达式的更多信息: http://en.wikibooks.org/wiki/F_Sharp_Programming/Computation_Expressions
You can read more about computation expressions on wikibooks: http://en.wikibooks.org/wiki/F_Sharp_Programming/Computation_Expressions
如果你想深入了解这背后的理论,你可以阅读Tomas Petricek和Don Syme撰写的这篇论文: http://www.cl.cam.ac.uk/~tp322/drafts/notations.pdf
And if you want to dive deeper into the theory behind this, you can read this paper by Tomas Petricek and Don Syme: http://www.cl.cam.ac.uk/~tp322/drafts/notations.pdf
这篇关于F#中的Int选项而不是Int#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!