パラメータ多相(parametric)
型のパラメータ化。静的。
length :: [a] -> Int length [] = 0 length (x:xs) = 1 + length xs
アドホック多相(ad-hoc)
型によって、異なる振る舞いを示す。静的。
class Shape a where display :: a -> String data Triangle = Triangle deriving Show instance Shape Triangle where display _ = " * \n" ++ " * * \n" ++ "*****\n" data Rectangle = Rectangle deriving Show instance Shape Rectangle where display _ = "*****\n" ++ "* *\n" ++ "*****\n"
putStr $ display Triangle → * * * ***** putStr $ display Rectangle → ***** * * *****
部分型多相(inclusion,subtyping)
継承による動的な多相性。関数の実体を、関数名をキーにして探索する。
data Polygon = forall a . (Shape a, Show a) => Polygon a instance Shape Polygon where display (Polygon x) = display x instance Show Polygon where show (Polygon a) = "Polygon " ++ show a
mapM_ putStr $ map display [Polygon Triangle, Polygon Rectangle] → * * * ***** ***** * * *****