Haskell中的泛型編程怎么實(shí)現(xiàn)

小億
86
2024-04-16 17:27:08
欄目: 編程語言

在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,并為IntChar類型實(shí)現(xiàn)了MyGeneric類型類的實(shí)例。接著我們定義了一個(gè)myGenericFunction函數(shù),根據(jù)傳入的類型不同,返回不同的字符串。最后在main函數(shù)中使用了myGenericFunction函數(shù)。這樣就實(shí)現(xiàn)了簡單的泛型編程。

0