What challenges might arise when integrating sum types into data exchange or configuration file formats such as json, protobuf, toml or yaml?

  • 2
    $\begingroup$ I’m voting to close this question because it asks multiple questions; all those data exchange formats are quite different and would have different approaches. $\endgroup$
    – Seggan
    Commented Nov 16, 2023 at 14:58
  • $\begingroup$ @RydwolfPrograms that's possible :p $\endgroup$
    – Ginger
    Commented Nov 16, 2023 at 15:49
  • 1
    $\begingroup$ @Seggan That sounds like 'needs more focus' to me. $\endgroup$
    – CPlus
    Commented Nov 16, 2023 at 22:20
  • $\begingroup$ @user16217248 ah yes of course theres a close reason i overlooked $\endgroup$
    – Seggan
    Commented Nov 16, 2023 at 22:55
  • 2
    $\begingroup$ What does "integrating sum types into ... json, protobuf, toml or yaml" even mean? Representing elements of sum types in those languages is already trivially easy. $\endgroup$ Commented Nov 20, 2023 at 20:07

2 Answers 2


Depending on how easy it is to differentiate the types, you might be forced to make sum types tagged. For example, a type float | int would be impossible to infer from JSON, as JSON.stringify({a: 1.0}) === '{"a":1}' on most JS implementations.

  • $\begingroup$ This looks like a union type to me, not a sum type. A sum type is a tagged union. $\endgroup$
    – kaya3
    Commented Nov 16, 2023 at 21:42
  • 1
    $\begingroup$ @kaya3 oops, I thought they were synonyms, tmyk $\endgroup$
    – kouta-kun
    Commented Nov 17, 2023 at 13:40

Swift has native sum types with enum, and serialization in the standard library with Codable. Codable is usually used for JSON, but it's meant to be format-agnostic. So, let's see how it handles this:

enum SumType: Codable {
  case i(Int)
  case d(Double)

It encodes this as a nested object (example):

{ "i": { "_0": 5 } }
// or
{ "d": { "_0": 0.5 } }

The key _0 is just the default as it's an unlabelled value; you're allowed to have things like this:

enum MyError {
  case unrecoverable(message: String)
  case recoverable(message: String, suggestions: [String])

In which case the keys of the inner object would be message and suggestions rather than _0 or similar.

This approach is amenable to JSON, YAML, and TOML, which all support nested objects. I'm not familiar with protobuf, but given how common nested structures are in code, I'd be very surprised if that doesn't support them.


Not the answer you're looking for? Browse other questions tagged .