xyncro / chiron

JSON for F#
https://xyncro.tech/chiron
MIT License
175 stars 41 forks source link

Does Chiron support generic type ? #75

Closed MangelMaxime closed 8 years ago

MangelMaxime commented 8 years ago

Hello guys,

I would like to support this type. The goal is to allow me to wrap my json response in this type to avoid to repeat myself. All the sub type which are going to replace the 'T type are supported by chiron.

type JsonResult<'T> =
    { Code: int
      Content: 'T
    }

    static member ToJson (x: JsonResult<'T>) =
         Json.write "Code" x.Code
      *> Json.write<'T> "Content" x.Content

The problem is I got this error: This code is not sufficiently generic. The type variable ^T when ( ^T or ToJsonDefaults) : (static member ToJson : ^T -> Json<unit>) could not be generalized because it would escape its scope.

Is this feature possible ? If yes could you help me please :)

[Edit]: I suppose I need to restrict the Type of 'T but don't know how.

kolektiv commented 8 years ago

Well, i've made it work... 😄 Two things need to change - the ToJson member needs to be inlined, and the type parameter needs to be named differently, to avoid indicating that it will always be the one given in the type declaration (as there isn't a way to apply the appropriate constraints to that one).

So, the following will actually work:

type JsonResult<'T> =
    { Code: int
      Content: 'T }

    static member inline ToJson (x: JsonResult<'U>) =
         Json.write "Code" x.Code
      *> Json.write "Content" x.Content

Although it doesn't seem like it should work, it does... It is beginning to get quite close to the edges of the F# type system though!

On a slightly different note - you might find that more specialised types actually help rather than the generic one. This approach would now lead to a potentially difficult to define data model from a consuming perspective. But you may not need to worry about that!

MangelMaxime commented 8 years ago

Thanks for the helps :)

And I think you could be right about more specialized types because finally I made used of HTTP Status Code and specialized each of my "bridge" between the browser and the server. It's means a little more code to support the different case but could by easier to evolve finally.

Thanks again for the help and great job on Chiron and Aether thus projects are awsome. :)

kolektiv commented 8 years ago

No problem! That solution sounds good, and as you say, the cost of a little extra code might make it easier to change without breaking things in future! Glad you're enjoying the libraries :)