|
|
|
|
|
by teo_zero
1045 days ago
|
|
Am I the only one lost at the very first paragraph? It shows something that looks like a grammar, but I can't understand what "Num", "Int", "If" are... Are they literals? terms? types? And what does "data" mean? So it's not a grammar. "data Exp" might describe each internal node of the AST, where the first word is the node's variety and the following words describe the children nodes. But what does "data Type" mean, then? |
|
You can think of them as enumerators that can possibly hold extra data.
The first definition (data Exp) is indeed a grammar. Thus "Num", "Int", "If" are just the names we give to different cases we encounter in the grammar. As for what they are... you can think of them as functions that wrap some data inside a struct of the same name (function names and type names don't collide). As for the name, they are called data constructors.
As for what "data" means, we are defining a new type which can hold some data (again). You can think of it as a synonym for "enum". The reason word "data" used here is because there's something called type synonyms. For example one can write:
type Email = String
type Password = String
Here the underlying representation for both email and password is string, but compiler treats Email and Password as another name for string. But if you were to use data constructors:
data Email = Email String
data Password = Password String
We are creating entirely new types. Even though the internal representation is still string, if we were to supply password when an email is expected, we get a compile error.
Essentially a wrapper class can do the same. But using data constructors we get the same benefit + something called pattern matching + exhaustive error checks + cleaner syntax + additional low-level optimizations by compiler.