Common Function Notation

I am trying to port a C # application to F # and I have this interface:

public interface ISerializer
{
    string ContentType { get; }
    string Serialize(object value);
    T Deserialize<T>(string value);
}

So, I would like to define a type like this:

type Serializer = {ContentType: string; Serialize: Object -> string; Deserialize<'T>: string -> 'T}

But I can not. What is the functional way here?

+3
source share
1 answer

You can define the same interface in F # as follows:

type ISerializer =
    abstract ContentType : string
    abstract Serialize : obj -> string
    abstract Deserialize<'a> : string -> 'a

It is not possible to get the same "internal" polymorphism with a natural functional data type such as a record, so you need to use OO constructs.

If you really wanted to use a record, you can define one wrapper for Deserializeand place it inside the record:

type IDeserializer =
    abstract Deserialize<'a> : string -> 'a

type Serializer =
    {
        ContentType : string
        Serialize : obj -> string
        Deserializer : IDeserializer
    }

but I don’t think it really is worth it.

+3
source

All Articles