Skip to content

Instantly share code, notes, and snippets.

@jacob-tock
Created November 18, 2015 17:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacob-tock/079ab0428b157d71dc26 to your computer and use it in GitHub Desktop.
Save jacob-tock/079ab0428b157d71dc26 to your computer and use it in GitHub Desktop.
Proposed format for Elm tagged unions as JSON-serialized objects
type T
= Constructor_1 cons1_1 ... cons1_j
| ...
| Constructor_n consn_1 ... cons2_k
value : T
value = Constructor_m consm_1 ... consm_i
JSON(Constructor_m consm_1 ... consm_i)
= { 'Constructor_m':
[ JSON(consm_1)
, ...
, JSON(consm_i)
]
}
{-
In other words, we represent an elm value of type T as a JSON object with one field whose name is the string
representation of the value's constructor and whose value is an array of (the json-serialized versions of)
the constructor's arguments, in order. So for a type like type
Shape = Rectangle Int Int | Circle Int | Point
, we'd have that
JSON(Rectangle 10 20) evaluates to { 'Rectangle': [10, 20] } and JSON(Point) evaluates to {'Point': []}.
This seems natural enough a representation of the concept. I think it'd be slightly more natural to represent
as something more like
{ 'type': 'Constructor_m',
'descriptive name for consm_1': JSON(consm_1),
...,
'descriptive name for consm_i': JSON(consm_i)
}
(that's for instance what they do in GeoJSON) but in this instance we don't have any descriptive names to use.
We could restrict serialization to tagged unions where each constructor takes either no arguments or a single record
argument, e.g., only allow
type Shape = Rectangle { length: Int, height: Int } | Circle { radius: Int } | Point
which would allow that other strategy to work. That might be nicer but I don't think that having a slightly nicer
JSON format justifies the restriction.
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment