Representing Heterogeneous Data

by grep_iton 10/1/23, 3:25 AMwith 14 comments
by elcritchon 10/1/23, 8:28 PM

> This is a real trade-off. The feature I have here provides strictly less static safety than using sum types. There is a slight performance cost to checking the type tag when accessing case-specific fields. In return, you get simpler, more familiar syntax for working with case-specific fields, including mutable ones.

Interesting post! Nim uses variant/case objects as well. Generally they're pretty handy and more flexible than sum types as you can access non-variant fields as regular objects. Though it means you can't use the same field name twice, however on the other hand you can bring common fields out of the case portion. Also, a single object can have multiple case variants which can be handy.

There's a PR for adding the stricter sum types and pattern matching as well. https://github.com/nim-lang/RFCs/issues/525 Currently I just use a library for sum type syntax on top of object variants: https://github.com/andreaferretti/patty

by gavinrayon 10/2/23, 3:02 AM

For what it's worth, the representation the author chose to go with is almost verbatim identical to how you declare variant object types in Nim.

by skybrianon 10/1/23, 11:31 AM

A bit surprising that this shows up here even though Bob apparently hasn’t figured out a good answer yet. Maybe someone will know a good solution?