What does has kind 'Constraint' mean in Haskell

前端 未结 2 646
孤街浪徒
孤街浪徒 2021-02-15 15:16

I am fresh to Haskell and I am trying to understand the language by writing some code. I am only familiar with very simple instructions on ghci: head, tail, sum, (*), and the li

2条回答
  •  不思量自难忘°
    2021-02-15 15:39

    As you are aware, values can be classified by their type. "foo" has type [Char], Just 'c' has type Maybe Char, etc.

    Similarly, types can be classified by their kind. All concrete types for which you can provide a value have kind *. You can see this using the :k command in GHCi:

    > :k Int
    Int :: *
    > :k Maybe Int
    Maybe Int :: *
    

    Type constructors also have kinds. They are essentially type-valued functions, so their kinds are similar to regular functions.

    > :t id
    id :: a -> a
    > :k Maybe
    Maybe :: * -> *
    

    But what is Num a? It's not a type, so it doesn't have kind *. It's not a type constructor, so it doesn't have an arrow kind. It is something new, so a new kind was created to describe it.

    > :k Num Int
    Num Int :: Constraint
    

    And Num itself is a Constraint-valued function: it takes a value of kind * and produces a Constraint:

    > :k Num
    Num :: * -> Constraint
    

    A thing with kind Constraint is used to specify the typeclass that a particular type must be an instance of. It is the value that can occur before => in a type signature. It is also the "argument" to the instance "function":

    instance Num Int where
      ...
    

提交回复
热议问题