30 ms·
This looks very nice. I've been working with sum types (as far as they can be called that) in Go a lot recently, and it's frustrating how bad it is as algebraic
by lobster_johnson 10y ago
This looks very nice. I've been working with sum types (as far as they can be called that) in Go a lot recently, and it's frustrating how bad it is as algebraic data types in general.
Aside from the lack of exhaustiveness checks, one particularly annoying area is writing code for enumeration and transformation. I needed one set of types to have this:
type Node {
Walk(WalkFunc)
TransformBottomUp(TransformFunc) (Node, error)
TransformTopDown(TransformFunc) (Node, error)
}
I implemented it as an interface precisely because of the lack of exhaustiveness checks, even though it feels wrong to attach code to my pure-data types.
But the code to do it is pure boilerplate. I considered doing something like having GetChildren() and SetChildren() and writing some generic transformer code, but they you have to deal with slices, which means a lot of allocation. I also considered having interfaces like Nonary, Unary, Binary, etc. that encapsulated the number of children, but that's terrible, too.
I might go with simple switch statements instead, and use this utility.