Haskell's algebraic data types

后端 未结 8 2163
我寻月下人不归
我寻月下人不归 2020-12-04 05:10

I\'m trying to fully understand all of Haskell\'s concepts.

In what ways are algebraic data types similar to generic types, e.g., in C# and Java? And how are they di

相关标签:
8条回答
  • 2020-12-04 06:09

    In universal algebra an algebra consists of some sets of elements (think of each set as the set of values of a type) and some operations, which map elements to elements.

    For example, suppose you have a type of "list elements" and a type of "lists". As operations you have the "empty list", which is a 0-argument function returning a "list", and a "cons" function which takes two arguments, a "list element" and a "list", and produce a "list".

    At this point there are many algebras that fit the description, as two undesirable things may happen:

    • There could be elements in the "list" set which cannot be built from the "empty list" and the "cons operation", so-called "junk". This could be lists starting from some element that fell from the sky, or loops without a beginning, or infinite lists.

    • The results of "cons" applied to different arguments could be equal, e.g. consing an element to a non-empty list could be equal to the empty list. This is sometimes called "confusion".

    An algebra which has neither of these undesirable properties is called initial, and this is the intended meaning of the abstract data type.

    The name initial derives from the property that there is exactly one homomorphism from the initial algebra to any given algebra. Essentially you can evaluate the value of a list by applying the operations in the other algebra, and the result is well-defined.

    It gets more complicated for polymorphic types ...

    0 讨论(0)
  • 2020-12-04 06:09

    @Timbo:

    You are basically right about it being sort of like an abstract Tree class with three derived classes (Empty, Leaf, and Node), but you would also need to enforce the guarantee that some one using your Tree class can never add any new derived classes, since the strategy for using the Tree datat type is to write code that switches at runtime based on the type of each element in the tree (and adding new derived types would break existing code). You can sort of imagine this getting nasty in C# or C++, but in Haskell, ML, and OCaml, this is central to the language design and syntax so coding style supports it in a much more convenient manner, via pattern matching.

    ADT (sum types) are also sort of like tagged unions or variant types in C or C++.

    0 讨论(0)
提交回复
热议问题