通用功能签名(Generic function signatures)

编程入门 行业动态 更新时间:2024-10-26 10:37:51
通用功能签名(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 -> 'a

There'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.

更多推荐

本文发布于:2023-08-01 11:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1357916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:功能   Generic   signatures   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!