How does Haskell handle overloading polymorphism?

前端 未结 6 1616
余生分开走
余生分开走 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:04

    Basically overriding is quite different in Haskell, although you can do something similiar.

    I. Use Classes as selected answer.

    class YesNo a where  
        yesno :: a -> Bool  
    

    You have to implement it using instance, and then you can use it like this:

    > yesno $ length []  
    False  
    > yesno "haha"  
    True  
    > yesno ""  
    False  
    > yesno $ Just 0  
    True  
    > yesno True  
    True  
    ghci> yesno EmptyTree  
    False  
    > yesno []  
    False  
    > yesno [0,0,0]  
    True  
    

    http://learnyouahaskell.com/making-our-own-types-and-typeclasses

    II. Use pattern matching of type constructor, such as:

    data Shape = Circle Float Float Float | Rectangle Float Float Float Float 
    surface :: Shape -> Float  
    surface (Circle _ _ r) = pi * r ^ 2  
    surface (Rectangle x1 y1 x2 y2) = (abs $ x2 - x1) * (abs $ y2 - y1)
    

    and then you can use them like this:

    > surface $ Circle 10 20 10  
    314.15927  
    > surface $ Rectangle 0 0 100 100  
    10000.0
    

    http://learnyouahaskell.com/making-our-own-types-and-typeclasses

    III. Have the "oveloaded" function in sepatate module, but you will need to prefix the import name or qualified imports name

    http://learnyouahaskell.com/modules

提交回复
热议问题