How does Haskell handle overloading polymorphism?

前端 未结 6 1609
余生分开走
余生分开走 2020-12-29 06:38

I have a question about Haskell polymorphism.

As I\'ve learned, there are two types of polymorphism:

  1. Parametric: where you do not spe

6条回答
  •  春和景丽
    2020-12-29 07:12

    Overloading in Haskell is done using type classes. For example, let's say you want to overload a function foo that returns an Int:

    class Fooable a where
        foo :: a -> Int
    
    instance Fooable Int where
        foo = id
    
    instance Fooable Bool where
        foo _ = 42
    

    However, they are more powerful than the overloading mechanisms found in most languages. For example, you can overload on the return type:

    class Barable a where
        bar :: Int -> a
    
    instance Barable Int where
        bar x = x + 3
    
    instance Barable Bool where
        bar x = x < 10
    

    For more examples, have a look at the predefined type classes in Haskell.

提交回复
热议问题