[英]Haskell's “deriving Show” in F#?
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. 在Haskell中,通过简单地将
deriving Show
添加到类型定义中,很容易将代数类型/区分联合“可显示”作为字符串。
In F# I end up writing things like: 在F#中,我最终写出如下内容:
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#? 有什么办法可以在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
). 如果使用
%A
格式说明符,则f#打印函数(如printf
可以合理地格式化任何数据类型(如果指定%O
则它们使用ToString
)。 You can implement ToString
using sprintf
which returns the formatted string: 您可以使用
sprintf
实现ToString
,它返回格式化的字符串:
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). 这打印例如“Pos(1,2)”,它适用于大多数F#类型(列表,联合,记录,元组)。 It's a bit longer than just adding
deriving Show
but at least you don't have to implement the printing yourself. 它比仅添加
deriving Show
长一些,但至少你不必自己实现打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.