Why is there a value constructor in addition to the type constructor in Haskell?

后端 未结 3 1084
余生分开走
余生分开走 2021-02-13 06:00

I\'m a newcomer to Haskell and am currently going through Real World Haskell. The book says the type constructor is used only in the type signature while the value constructor i

3条回答
  •  半阙折子戏
    2021-02-13 06:40

    It's a bit like saying "why do we need classes and objects if objects are the only thing that actually runs?"

    The two sorts of constructors do different jobs. Type constructors go in type signatures. Value constructors go in runnable code.

    In the simplest case, a type "constructor" is just a type name. In the simplest case, a type has only one value constructor. So you end up with things like

    data Point = Point Int Int

    You might say to yourself "now why the heck to I need to write Point twice?"

    But now consider a less trivial example:

    data Tree x = Leaf x | Branch (Tree x) (Tree x)

    Here Tree is a type constructor. You give it a type argument, and it "constructs" a type. So Tree Int is one type, Tree String is another type, and so on. (Like templates in C++, or generics in Java or Eiffel.)

    On the other hand, Leaf is a value constructor. Given a value, it makes a 1-node tree out of it. So Leaf 5 is a Tree Int value, Leaf "banana" is a Tree String value, and so on.

    Similarly for Branch. It takes two tree values and constructs a tree node with those trees as children. For example, Branch (Leaf 2) (Leaf 7) is a Tree Int value.

提交回复
热议问题