Why “Algebraic data type” use “Algebraic” in the name?

前端 未结 2 1407
-上瘾入骨i
-上瘾入骨i 2021-01-12 13:06

When I learn Scala/Haskell, I see there is a concept of Algebraic data type. I\'ve read the explanation from the wikipedia, but I still have a question:

Why does it

2条回答
  •  走了就别回头了
    2021-01-12 13:45

    In simple words we must consider here relationship between algebra and types. Haskell's algebraic data types are named such since they correspond to an initial algebra in category theory.

    Wikipedia says:

    In computer programming, particularly functional programming and type theory, an algebraic data type is a kind of composite type, i.e. a type formed by combining other types.

    Let's take Maybe a data type:

    data Maybe a = Nothing | Just a
    

    Maybe a indicates that it might contain something of type a - Just Int for example, but also can be empty - Nothing. In haskell types are objects, for example Int. Operators gets types and produces new types, for example Maybe Int. Algebraic refers to the property that an Algebraic Data Type is created by algebraic operations: sums and product where:

    • "sum" is alternation (A | B, meaning A or B but not both)
    • "product" is combination (A B, meaning A and B together)

    For example, let's see sum for Maybe a. For the start let's define Add type:

    data Add a b = Left a | Right b
    

    In haskell | is or, so it can be or Left a or Right b. Vertical bar | shows us that Maybe which we defined above is a sum type, it means that we can write it with Add:

    type Maybe a = Add Nothing (Just a)
    

    Nothing here is here is a unit type:

    In the area of mathematical logic and computer science known as type theory, a unit type is a type that allows only one value

    data Unit = Unit
    

    Or () in haskell.

    Just a is a singleton type as. Singleton types are those types which have only one value.

    data Just a = Just a
    

    After it we can rewrite it as:

    type Maybe a = Add () a
    

    So we have unit type - 1, and singleton type which is - a. Now we can say that Maybe a is the same as 1 + a.

    If you want to go deep - The Algebra of Data, and the Calculus of Mutation

提交回复
热议问题