如何在 F# 中定义一个非零整数,在分配零值时会引发编译时错误?
我的问题来自观看此 Scott Wlaschin 视频 https://www.youtube.com/watch?v=E8I19uA-wGY&t=960s在 16:00 分钟内
我在 SO 中找到了这个问题的另一个答案,但都是指动态检查(在创建时抛出异常),但这种方法没什么大不了的,可以在任何 OO 而不是 OO 语言中完成。我在看的是这样的:type NonZeroInteger = int except 0
或类似的东西。
最佳答案
在 F# 中,您想要做的事情并没有真正的编译时间契约。处理此问题的 F# 方法是使用类型 NonZeroInteger
带有一个私有(private)构造函数和一个返回 Option<NonZeroInteger>
的函数.这将确保您永远不会拥有 Some(0)
.
这样做基本上是迫使使用您的代码的开发人员考虑他可能没有 NonZeroInteger
的可能性。在构造一个之后,当给定错误的整数值时。
在您的代码中,您始终可以安全地假设 NonZeroIntegers 实际上是非零的。
open Option
module A =
type NonZeroInteger =
private | NonZeroInteger of int
static member Create (v : int) : Option<NonZeroInteger> =
if v = 0 then
None
else
Some(NonZeroInteger(v))
member this.Get : int =
this |> fun (NonZeroInteger v) -> v
member this.Print =
this |> fun (NonZeroInteger v) -> printfn "%i" v
printfn "%A" (A.NonZeroInteger(0)) // error FS1093: The union cases or fields of the type 'NonZeroInteger' are not accessible from this code location
let wrong = A.NonZeroInteger.Create(0) // None
let right = A.NonZeroInteger.Create(-1) // Some
wrong |> Option.iter (fun x -> x.Print) // Doesn't print anything
right |> Option.iter (fun x -> x.Print) // Prints -1
private
构造函数防止你的模块之外的任何人构造 NonZeroInteger
无需通过您的 Create 函数。这使得代码非常冗长和缓慢,但安全。所以这里肯定有一个权衡。
关于types - 在 F# 中定义非零整数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45626196/