Jon Canning
Jon Canning

Reputation: 1642

Generic function signatures

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?

Upvotes: 3

Views: 138

Answers (1)

Ganesh Sittampalam
Ganesh Sittampalam

Reputation: 29110

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.

Upvotes: 3

Related Questions