Can someone explain why this whole thing about cre...
# functional
p
Can someone explain why this whole thing about creating sealed classes with different types and all that, why is called
algebraic data types
? What's the relationship with algebra?
solved 1
NVM I found a lot of resources describing where the name comes from.
f
Feel free to share your favorites 🙂
g
The idea is that there are two type of types. 1. The “product” types (i. e. normal structs). They are called “product” because the possible values is the product of the possible values of each field in the structure. If you have a
data class X(val f1: Int, val f2: Boolean)
you can take all possible values of Int for
f1
and multiply it by the possible values if
f2
(Boolean = 2). 2. the “sum” types Kotlin does not really have sum types but the behaviour can be modeled with sealed classes. Because there can be only one instance of one of the sub classes at a time, the resulting possibilities is not multiplied but added. Look at the example in Rust (where it is easier to see):
Copy code
enum SumType {
  Unconfirmed(s: String),
  Confirmed(s: String),
}
Each value of
SumType
can be either
Unconfirmed
having a string as payload ‘or’ be
Confirmed
also having a string as payload. So the resuling possibilities is not String ‘times’ String but String ‘plus’ String. Don’t worry, in real life no-one cares about this explanation. It is just that you model different possibilities but with a payload each. Kotlins
enum
cannot do that but with
sealed class
you can have the same funtionality. In Languages like Rust, Ocam, F# or Haskell, these types are much easier to describe.
🏆 3
scala 1
p
Thanks 🙏 I could find similar information here: https://en.wikipedia.org/wiki/Algebraic_data_type This medium article very well explains it: https://code.egym.de/a-brief-introduction-to-the-algebra-of-types-df92f0820e5
g
In the end, it’s just a name, like so many others. Who cares, why a Monad is called a Monad?
😁 2