在Haskell中,泛型編程通常通過類型類和多態(tài)函數(shù)來實(shí)現(xiàn)。下面是一個(gè)簡單的例子:
-- 定義一個(gè)類型類
class MyGeneric a where
myGenericFunction :: a -> String
-- 定義一個(gè)多態(tài)函數(shù)實(shí)例
instance MyGeneric Int where
myGenericFunction x = "This is an Int: " ++ show x
instance MyGeneric Char where
myGenericFunction x = "This is a Char: " ++ [x]
-- 使用多態(tài)函數(shù)
main = do
putStrLn $ myGenericFunction (5 :: Int)
putStrLn $ myGenericFunction 'a'
在這個(gè)例子中,我們定義了一個(gè)類型類MyGeneric
,并為Int
和Char
類型實(shí)現(xiàn)了MyGeneric
類型類的實(shí)例。接著我們定義了一個(gè)myGenericFunction
函數(shù),根據(jù)傳入的類型不同,返回不同的字符串。最后在main
函數(shù)中使用了myGenericFunction
函數(shù)。這樣就實(shí)現(xiàn)了簡單的泛型編程。