types - 在 F# 中定义非零整数类型

标签 types f# integer subdomain

如何在 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/

相关文章:

golang 错误处理类型不匹配

database - F# - 依赖管理

string - F# 字符串到枚举的转换

.net - 将 String.Empty 转换为 Nothing/Null

c++ - 程序精度因参数而异

python - 条件如果字符串仅包含变量和整数Python

.net - 检查 c# 7 中 Valuetuple 列表中的各个项目

arrays - 来自数组类型的 Typescript 接口(interface)

传递给函数时对象中键的 typescript 缩小

.net - 在签名文件中共享受歧视的联合