What does the => symbol mean in Haskell?

后端 未结 4 1940
礼貌的吻别
礼貌的吻别 2020-12-13 06:54

I\'m new to Haskell and, in general, to functional programming, and I\'m a bit uncomfortable with its syntax.

In the following code what does the =>

相关标签:
4条回答
  • 2020-12-13 06:58

    On the left hand side of the => you declare constraints for the types that are used on the right.

    In the example you give, it means that a is constrained to being an instance of both the Ord type class and the Num type class.

    0 讨论(0)
  • 2020-12-13 07:03

    This is a typeclass constraint; (Num a, Ord a) => ... means that loop works with any type a that is an instance of the Num and Ord typeclasses, corresponding to numeric types and ordered types respectively. Basically, you can think of loop as having the type on the right hand side of the =>, except that a is required to be an instance of Num and Ord.

    You can think of typeclasses as basically similar to OOP interfaces (but they're not the same thing!) — they encapsulate a set of definitions which any instance must support, and generic code can be written using these definitions. For instance, Num includes numeric operations like addition and multiplication, while Ord includes less than, greater than, and so on.

    For more information on typeclasses, see this introduction from Learn You a Haskell.

    0 讨论(0)
  • 2020-12-13 07:06

    => separates two parts of a type signature:

    • On the left, typeclass constraints
    • On the right, the actual type

    So you can think of (Num a, Ord a) => a -> (t -> t) -> t -> t as meaning "the type is a -> (t -> t) -> t -> t and also there must be a Num instance for a and an Ord instance for a".

    For more on typeclasses see http://www.learnyouahaskell.com/types-and-typeclasses

    0 讨论(0)
  • 2020-12-13 07:22

    One way to think about it is that Ord a and Num a are additional inputs to the function. They are a special kind of input though: dictionaries. When you use this function with a particular type a, there must also be dictionaries available for the Ord and Num operations on the type a as well.

    Any function that makes use of a function with dictionary inputs must also have the same dictionary inputs.

    foo :: (Num a, Ord a) => a -> t
    foo x = loop x someFunc someT
    

    However, you do not have to explicitly pass these dictionaries around. Haskell will take care of that for you, assuming there is a dictionary available. You can create a dictionary with a typeclass instance.

    instance Num MyType with
      x + y = ...
      x - y = ...
      ...
    

    This creates a dictionary for the Num operations on MyType, therefore MyType can be used anywhere that Num a is a required input (assuming it satisfies the other requirements, of course).

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