哈斯克尔的“衍生秀”在 F# 中?
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用
%A
格式说明符,F# 打印函数(例如printf
)能够合理地格式化任何数据类型(如果您指定,它们将使用ToString
%O
)。您可以使用sprintf
实现 ToString,它返回格式化字符串:这会打印例如“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 useToString
if you specify%O
). You can implementToString
usingsprintf
which returns the formatted string: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.