Haskell's algebraic data types

后端 未结 8 2193
我寻月下人不归
我寻月下人不归 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 ...

提交回复
热议问题