哈斯克尔的“衍生秀”在 F# 中?

发布于 2024-08-22 07:55:34 字数 381 浏览 4 评论 0原文

在 Haskell 中,只需将 deriving Show 添加到类型定义中,即可轻松将代数类型/可判别联合“显示”为字符串。

在 F# 中,我最终写了这样的内容:

type Pos = 
    | Pos of int * int
    override this.ToString() = 
        match this with
        Pos(startp, endp) -> sprintf "Pos(%d, %d)" startp endp

显然,对于更复杂的类型,情况会变得更糟。

有什么方法可以在 F# 中获得类似 deriving Show 的东西吗?

In Haskell it is easy to make an algebraic type/discriminated union "displayable" as a string by simply adding deriving Show to the type definition.

In F# I end up writing things like:

type Pos = 
    | Pos of int * int
    override this.ToString() = 
        match this with
        Pos(startp, endp) -> sprintf "Pos(%d, %d)" startp endp

and obviously it gets much worse with more complicated types.

Any way to get something like deriving Show in F#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝咒 2024-08-29 07:55:35

如果您使用 %A 格式说明符,F# 打印函数(例如 printf)能够合理地格式化任何数据类型(如果您指定,它们将使用 ToString %O)。您可以使用 sprintf 实现 ToString,它返回格式化字符串:

type Pos =  
    | Pos of int * int 
    override x.ToString() = sprintf "%A" x 

这会打印例如“Pos (1, 2)”,并且适用于大多数 F# 类型(列表、联合、记录、元组)。它比仅仅添加deriving Show要长一些,但至少您不必自己实现打印。

F# printing functions such as printf are able to format reasonably any data type if you use the %A format specifier (they use ToString if you specify %O). You can implement ToString using sprintf which returns the formatted string:

type Pos =  
    | Pos of int * int 
    override x.ToString() = sprintf "%A" x 

This prints for example "Pos (1, 2)" and it works for most of the F# types (lists, unions, records, tuples). It's a bit longer than just adding deriving Show but at least you don't have to implement the printing yourself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文