5 ms·
I'd say that 2 is indeed quite common in Computer science. In graphs, for example, each edge has 2 ends. In an abstract syntax tree, a binary operator has 2 chi
by teo_zero 4y ago
I'd say that 2 is indeed quite common in Computer science. In graphs, for example, each edge has 2 ends. In an abstract syntax tree, a binary operator has 2 children. All raster images are based on 2 dimensions. A "for each" loop often involves 2 variables: the iterator object and an index.
In all such cases it makes sense that a language/ construct/library special-cases 2 elements without generalizing for an arbitrary number of elements.
By the way, 3 is much less common, except in some specific domains, like 3D vectors, UNIX permissions (user, group, other), etc.
- Kim_Bruning 4y agoOh, you're right, there are a few other exceptions for other numbers too!
- xigoi 4y agoUsually you wouldn't store these things in a collection, but as separate fields of a record type, so the rule doesn't apply.
- teo_zero 4y agoThe principle applies to all kinds of structures. For example a common way to implement a generic tree that respects this rule is to model each node with exactly one parent and any number of children. My statement instead is that you may have legitimate reasons to want exactly one parent and from zero to two children, but not more.
- deleted 4y ago[deleted]
- xigoi 4y agoWhat would be the use case of such a tree?
- teo_zero 4y agoAn Abstract Syntax Tree, where each node can have zero children (e.g. a literal value), one child (unary operator like 'Not') or two children (a binary operator like +).
- xigoi 4y agoAnd what exactly is the benefit of restricting such a tree to two children? Why not just allow an arbitrary amount of children and then only use it with 0,1,2? After all, you might later want to extend the language.
- teo_zero 4y agoAllowing arbitrary number of children doesn't come for free. You might need a linked list, which is a waste of memory and access time if you always just use up to two elements. What most parsers do is to provide exactly 2 slots, aptly named left and right, and use zero, one or both of them.