How does Haskell handle overloading polymorphism?

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

    Here, you have a simple example combining

    • ad-hoc polymorphism (overloading): same function with different behavior for different types (by means of Haskell type classes)

    • parametric polymorphism: same function with same behavior for different types (by means of a type parameterized function. In principle, type doesn't matter, but we used type classes to restrict acceptable types).

    Code:

    import Data.Char
    
    class MyTypeFamily t where
          f1 :: t -> Int
          f2 :: t -> Int
    
    instance MyTypeFamily Int where
             f1 x = x*x
             f2 x = x+x
    
    instance MyTypeFamily Char where
             f1 x = (ord x) * (ord x)
             f2 x = (ord x) + (ord x)
    
    instance MyTypeFamily Bool where
             f1 x 
                | x = 10
                | otherwise = 10 
             f2 x 
                | x = 100
                | otherwise = -100
    
    -- ...............................................................
    -- using f1, f2 as "overloaded" functions ("ad-hoc polymorphism)
    --  (the algorithm for f1, f2 is chosen depending on their type)
    --
    -- using  fun as polymorphic (parametric polymorphic function)
    -- the algorithm of fun is always the same but it works on
    -- different types
    fun :: (MyTypeFamily t) => t -> Int
    fun x = (f1 x) + (f2 x) 
    
    -- ...............................................................
    -- ...............................................................
    main =  do
            print $  fun 'J'
            print $  fun True
            print $  fun False
            print $  fun (8 :: Int)
    

提交回复
热议问题