Tip: parents vs sets of children

A common question I’ve seen from beginners is whether it’s better to make a parent relation or a set of child relations, like so:

-- which field is better?

sig Parent {
  children: set Child

sig Child {
  parent: Parent

First of all, a common beginner mistake is people thinking they need both. Since any relation is invertible with ~, you only need one: parent = ~children and vice versa. In fact having one is preferable, since you don’t need to add a fact to keep them in sync.

So the choice should instead depend on structural concerns. Each creates a different set of possible models. With set children, it’s possible for multiple Parents to share a Child. It’s also possible for a Child to not have any Parents. With parent, you guarantee that every Child has exactly one Parent.

I generally find that using parent or lone parent is preferable unless my domain explicitly permits having multiple Parents share children.



Just to complement with a related tip…

Let’s suppose you decide to declare the parent relation only, but you would still want to have children for convenience when specifying constraints or to have better visualisations. Instead of declaring it and add a fact stating that children = ~parent I prefer to have a function that computes its value, because less solving variables are created and, in principle, analysis will be more efficient. children will be a function without parameters that returns a relation from Parent to Child and can be defined as follows:

fun children : Parent -> Child {

Since children is a derived relation it will be also visualised by the Analyzer and its depiction can be customised with themes likewise any other relation.