通用功能签名(Generic function signatures)
我正在努力将C#应用程序移植到F#,我有这个界面:
public interface ISerializer { string ContentType { get; } string Serialize(object value); T Deserialize<T>(string value); }所以我想定义一个这样的类型:
type Serializer = {ContentType: string; Serialize: Object -> string; Deserialize<'T>: string -> 'T}但我不能。 这里的功能方式是什么?
I'm endeavouring to port a C# app to F# and I have this interface:
public interface ISerializer { string ContentType { get; } string Serialize(object value); T Deserialize<T>(string value); }So I'd like to define a type like this:
type Serializer = {ContentType: string; Serialize: Object -> string; Deserialize<'T>: string -> 'T}But I can't. What's the functional way here?
最满意答案
您可以在F#中定义相同的界面,如下所示:
type ISerializer = abstract ContentType : string abstract Serialize : obj -> string abstract Deserialize<'a> : string -> 'a没有办法使用自然的功能数据类型(如记录)获得相同的“内部”多态性,因此您必须使用OO结构。
如果您真的想要使用记录,可以为Deserialize定义一个包装Deserialize并将其放入记录中:
type IDeserializer = abstract Deserialize<'a> : string -> 'a type Serializer = { ContentType : string Serialize : obj -> string Deserializer : IDeserializer }但我认为这不值得。
You can define the same interface in F# like this:
type ISerializer = abstract ContentType : string abstract Serialize : obj -> string abstract Deserialize<'a> : string -> 'aThere's no way to get the same "internal" polymorphism with a natural functional datatype such as a record, so you have to use the OO constructs.
If you really wanted to use a record, you could define a single wrapper for Deserialize and put that inside a record:
type IDeserializer = abstract Deserialize<'a> : string -> 'a type Serializer = { ContentType : string Serialize : obj -> string Deserializer : IDeserializer }but I don't think it's really worthwhile.
更多推荐
发布评论