2

What is the correct type for serializing Maybe types?

Given I have some data structure of Maybe type on the server and I serialize it with showToFay function, then it won't become one of the {"instance":"Nothing"} or {"instance":"Maybe","slot1":<actual_value>}, but it is serialized as either null or bare inside of the Just. Then it's not possible for me to deserialize it on the client correctly.

I'm using the data MyMaybe a = MyNothing | MyJust a type for now, but it's hard to do with as I need to pattern match all the time and I can't use the combinators defined on Maybe.

ryskajakub
  • 6,351
  • 8
  • 45
  • 75
  • 1
    Unfortunate, sounds like a bug or misfeature. – luqui Jan 26 '15 at 17:16
  • 1
    I wouldn't say there is some correct type for serializing `Maybe a`. You could use aeson to read and write a `Maybe a` to/from JSON, provided you know how to read and write `a` to/from JSON. Or, you could use binary serialization from the cereal package. Both of these packages will work seamlessly with `Maybe a` provided `a` has the relevant instances defined. As far as I can tell, `showToFay` is for converting a Haskell value into something that a JavaScript interpreter could `eval()`. I don't think it's intended for serialization. – Alexander Vieth Jan 26 '15 at 17:36
  • Just to clarify, if you know the type on both ends, this misfeature only makes deserialization impossible if you have something like `Maybe (Maybe T)`, since then you can't discriminate between `Nothing` and `Just Nothing`. – Cactus Jan 27 '15 at 02:17
  • need to pattern match all the time - perhaps not, you can write instances for Monad, MonadPlus, etc. – d8d0d65b3f7cf42 Jan 27 '15 at 09:12
  • @AlexanderVieth I think you could turn your comment into an answer -- it is very much to the point. – sclv Feb 21 '15 at 16:41

0 Answers0