I want to store a list of "things" which can have some optional extra attributes attached to them. Each thing can have one or more attributes. And different attributes are of different types.
I want to be able to create literal lists of these things concisely in code. But I'm having trouble seeing how to get this past the type system because tuples allow mixtures of types but are fixed length, while lists are variable length but one type.
This is a toy example of what I want to be able to do :
things = [
Thing 1 RED,
Thing 2 RED LARGE,
Thing 3 BLUE SMALL,
Thing 4 SMALL,
Thing 5 BLUE DOTTED
]
etc.
What's the right way to do this?
There are various ways to implement heterogeneous collections in Haskell, but using a list of arbitrary values of arbitrary types is probably more flexibility than you need, and more trouble than it's worth. You're probably better off creating one type with an expressive set of possible values, and using a homogeneous collection of that.
Your example attributes appear to fall into a set of known categories: color (e.g. RED, BLUE), size (e.g. LARGE, SMALL), and what I'll call "texture" (e.g. DOTTED). A
Thing
doesn't necessarily have an attribute in each category, but I'll assume that it shouldn't have more than one attribute in the same category — it doesn't make sense for a singleThing
to be both LARGE and SMALL.You could represent these categories as algebraic data types:
and combine them with a data structure:
Now you can just associate a single
ThingAttributes
value with eachThing
.If you do want to allow multiple attributes in the same category (e.g. having a
Thing
that's both LARGE and SMALL), you can use another algebraic data type to bring all the category types together:and then associate a
Set ThingAttribute
— or simply a[ThingAttribute]
if you don't mind duplicates of the same attribute — with eachThing
.Basically, rather than storing the attributes as given, you should store the resultant properties of a chord with these attributes. One simple (but not really nice, musically) solution would be, storing only the final pitches:
To be used as e.g.
A more sophisticated approach might actually store the information about a chord in a more musically meaningful way:
This can be used in much the same way, but is more versatile.
If you don't like giving the attributes as prefix functions, you can do as the diagrams package, with
to write
Let's say Chords are collections of Notes.
But also with optional sets of Annotations
We can model Chords thus as
We can build an entire vocabulary this way
And then build our list like so