But where are those 'algebraic' operations in code snippet above?
They are implicit in the syntax of the language. The conceptual operation of "addition"
A + B
can be encoded in Scala as
sealed trait T
case object A extends T
case object B extends T
whilst conceptual operation of multiplication
A x B
can be encoded in Scala as
case class T(a: A, b: B)
What is algebraic about ADT
The term "algebra" has roots in mathematical field called abstract algebra. It is an endeavour which looks into different objects and different operations on those objects and hopes to find common behaviours between them. Roughly it is the process of taking away things and seeing what remains. Like when you learn to count and do arithmetic with apples as a child. At some point you "take away" the apples, and what remains are "numbers" which behave the same way as apples. The advantage of that is that now the same rules and laws you learned with arithmetic of apples, generalise to arithmetic of oranges and beyond. But mathematicians go even further and ask crazy question like what happens if we take away even the numbers themselves? Another way of looking at it is you write down some equation like
a + b = b + a (commutativity law)
where addition +
is defined in some abstract sense, and now try to find any kind of object that satisfy it. For example, integers satisfy it, as well as real numbers, etc., but turns out also certain kind of data types like sum types fit into that equation. So then mathematicians declare all the classes of objects, collectively, which work with addition operation in some sense, such that the result of the operation is commutative, as an algebraic structure, and give it some grand name like Abelian group etc. This is roughly the etymology of "algebraic" in "algebraic data type".
Bool
is the sum ofTrue
andFalse
. – VLAZ