溫馨提示×

Haskell中的泛型編程怎么實現

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

在Haskell中,泛型編程通常通過類型類和多態函數來實現。下面是一個簡單的例子:

-- 定義一個類型類
class MyGeneric a where
  myGenericFunction :: a -> String

-- 定義一個多態函數實例
instance MyGeneric Int where
  myGenericFunction x = "This is an Int: " ++ show x

instance MyGeneric Char where
  myGenericFunction x = "This is a Char: " ++ [x]

-- 使用多態函數
main = do
  putStrLn $ myGenericFunction (5 :: Int)
  putStrLn $ myGenericFunction 'a'

在這個例子中,我們定義了一個類型類MyGeneric,并為IntChar類型實現了MyGeneric類型類的實例。接著我們定義了一個myGenericFunction函數,根據傳入的類型不同,返回不同的字符串。最后在main函數中使用了myGenericFunction函數。這樣就實現了簡單的泛型編程。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女